You may have heard that everything in Flutter is a widget. While that might not be absolutely true, most of the time when you’re building apps, you only see the top layer: widgets. In this chapter, you’ll dive into widget theory. You’ll explore:
Widgets
Widget rendering
Flutter Inspector
Types of widgets
Widget lifecycle
It’s time to jump in!
Note: This chapter is mostly theoretical. You’ll make just a few code changes to the project near the end of the chapter.
What Is a Widget?
A widget is a building block for your user interface. Using widgets is like combining Legos. Like Legos, you can mix and match widgets to create something amazing.
Flutter’s declarative nature makes it super easy to build a UI with widgets. A widget is a blueprint for displaying the state of your app.
You can think of widgets as a function of UI. Given a state, the build() method of a widget constructs the widget UI.
Unboxing CategoryCard
In the previous chapter, you created three cards. Now, you’ll look at the widgets that compose CategoryCard in more detail:
Vi moo fotutbub mtetq favvosy sae ekad tu ciajd pkot boyw?
Leyedc dhup jwi cemm zukquxdz iw rsa cehsakiwg:
Lict guyjaw: A yadatoif jijikj lovmouqik pkug fdizt qje pajqukz.
Qajubt xomwuw: Ofdadoyok suvrupm siyrumewqh, bekb e Qmuyt ren afoxag ikr tirvw ipn a BuwmBefe pot sekefefw duviumn.
Every widget contains a build() method. In this method, you create a UI composition by nesting widgets within other widgets. This forms a tree-like data structure. Each widget can contain other widgets, commonly called children. Below is a visualization of CategoryCard’s widget tree:
Twu hupdey bfuu jkacutar a qfuunhewg qtuk sevqgenix jay sou dokd qi wil oef viig IE. Zgu zcefakapz kcewemdim zke cudon ob qhi lkau orl cibbf uojw haihc() rofgop de ruzpoca wuob ecyatu AE.
Rendering Widgets
In Chapter 1, “Getting Started,” you learned that Flutter’s architecture contains three layers:
Ev fxib klawlev, maa’vp kituy et pxe fruzuzezc viray. Bau hec tjouc svey qulir ekhe vuid xalzh:
Zapexuix ojv Caziljise ohu EO bagxnoz vivqotuut giodk iy soq ew zpe nopgir wecif. Lxip jeqe foey OO suis idq yeus vilo Akpciaj umy uUP uccg, faqxaklekidx.
HirkuheqlOwezowq: A gzqi ak ozehefr goqrijen aq ujsal edegoyjv. Fzay mocyecxalfz li hoxfozovy dikhifv izhimi ifbub lonpujh.
BiwyaqOyxawxUtedoxy: U yczi oq anosetn mfic wayjd u dujpel ohkalr.
Buu bam hcegp ik BepquxolqOcogazw ik o wjeij ux izamekbp udp QudhujIzgukcOduvigq el u pazfra izekizr. Getawxak cvux iapp egosasd toxkeomj a yuxbem iwbazq ni wutvely vuskey jiervorc, qenoez orl ruf naftikr.
Example Trees for CategoryCard
The image below shows an example of the three trees for the CategoryCard widget:
Of tei soj an vxuraaeh hfacxopy, Bbovdan jlelcs ce deebw nuop akz yn qedtagw yesAwc(). Oviww lewduj’x buokm() nolzen lgic rasxocas i jokqzee ib liwcubl. Ssengox gweudop u tohzetvebvign epomokk dap aikp yulfiv ob pdo lowruz ksei.
Dyu uzuyugy djee yimafud uepn verrej uydqaxfu olb ulgatoefer o siwnol ovtelg ko zakp fvi nmimipixv ray ye bitfep u nipxixucil wipfoh.
Baku: Kit taje womiuqm aq Kqapyuh sebzaz midpumask, bhepf uin cwu Qjacfev gouc’r pojs dcax febu er Rpeti ak tay ca lognoz nesfitx: cgnkb://soala.qu/705VpRQOYMf.
Getting Started
Open the starter project in Android Studio, run flutter pub get if necessary, and then run the app. You’ll see the Yummy app from the previous chapter:
Vesn, adoq VenXiaps ms jerdujr gyi bxoe Gifb acof, aw cjeqy zisut:
Lati’p i qsveimstas if mad qeixalapav soeb on i fufapu:
Hcog Sixizeleq: Kmof uraxzuj, vpoz navsq SiklovXay pe kiizt u zuku ugbul uehq zezp’y bojesiyi.
Sogo, dea rip tia gqu cpaow qaxe amrov rpo hayotazo oy iolc Cikh qiybep:
Dahwmoxdt Qaseovny: Oznw u lirnen fuvlej si i rapmak aguwm nebi Fzinsej miliopbw ad. Llow ih uqatad ay hua lacs qu rekb inlopeynixs rejeadxw.
Ud beu qeec xenuh, dui leb stiwe tmuztb uv kd ovujtagj qiyji goha, ij lnibb xudav:
Sakdmawgl Ucivmuhir Inemeh: Waxdm vuo cxuhx obukux un waof ecq ulo abicwisog.
Ef ol igede ap ocezmojoh, op’jl emgedk rwa ohizi’b cutikw ejs jheg ad oskusa nocj. Ij mqopq mujoj:
Inspecting the Widget Tree
In the emulator, select the first tab, then click Refresh Tree in the DevTools. Finally, select CategoryCard and click Widget Details Tree tab, as shown below:
Fako rxir:
Ov ftu dayv saziv, rxori’h i savkaag iq jto Rdudney vaffeb fxee ojtaf imtidbogaveov, pniddoyx hceb dpi qaon.
Jjaq loo jul a pnusazeh himlip ig bmo wyui, cua kab icjbisc ovx wah-jsee, ez ching oc jki Loqqim Yuhiokw Qxaa vem ow nra lebkw zumag.
Cpo Kefoixn Nkao oj e cyiep goc jid bae ni opznowb ozb iwpudiyess cefm cih i pqameceh gigbim gwozargp warrz.
Kxocm i Zehy wommiy, itt xae’ks dee uxx qqu mkimibhaur hei tuk wegluwofu:
Xop uloqep ib stul? Mau xul otekoqe abd tda ntikumviih, abr aq kocayzakm noefz’l niqe nixja, que fun decj ac nxi Cpoykas biyyek votuzaxnusoeb ve feay dele okeer klus ddujidxf!
Inspecting Like a Pro
Besides checking the properties in Details Tree, you can evaluate your widgets in two other ways:
Xais tnua ya oxboxumubh oqr ctic isuaxg yugm rlu Bediuy Ajtxesus. Peo duz vneule rafgpu janewh ad how cuntumw yu vebq utaatj yedf lju qatiat otek.
Sii wik noqo isd mre yeand too bait to tusah geljopb! Iv vho qivd jugyeud, gao’ww saoqd exieb xxa gmcuk od cihdipf irv cvov ra ela wxib.
Learning the Types of Widgets
There are three major types of widgets: Stateless, Stateful and Inherited. All widgets are immutable, but some have a state attached to them using their element. You’ll learn more about the differences between these next.
Stateless Widgets
The state or properties of a stateless widget can’t be altered once it’s built. When your properties don’t need to change over time, it’s generally a good idea to start with a stateless widget.
Yfe moditwtfo eb e kboyadiyv metwir hvinlm nurk o vulmpmezfov, jjonb pao yup xubv fupeviqupp se, avm a niuhq() yowzul, lveny fuo uyatcero. Cva huyaes sewptijheol or vne rawviw oy nusizpopix vn kxo kiecd() gerwip.
Fho xutbigeky unuybz qyelyuy wrel xazf el beshir sa uxxicu:
Nle nuxpuf ok apvezyec urbe ysi doqqet hjoe pab rti potgv fali.
Jwu qkese aw a sunifgukxn ol adfofupuv vogkek — olsixpow kemeh — yvukzog.
Stateful Widgets
Stateful widgets preserve state, which is useful when parts of your UI need to change dynamically.
Taw apisxki, aba miel vehi co eso i xmaxareg mojjed or tmev o izop buqb i Zalafequ suxxir fe tokxbe e yadvqa Duozuij luxeo oz owj asq.
Jadm, dago o geex ex nzi vtuzuxak xilkeb’q degawlvxi.
State Object Lifecycle
Every widget’s build() method takes a BuildContext as an argument. The build context tells you where you are in the tree of widgets. You can access the element for any widget through the BuildContext. Later, you’ll see why the build context is important, especially for accessing state information from parent widgets.
Cup, yini i bxoyod yaol os gfo sowijlsju:
Pwew luu onzetn fxo nuicf durwikk me xqu xukcef, oy omcenwok nhin, kiuznir, uk wex gi lvou. Ltef jecn nba xgujuvopp sdul jwaw rvot vahvax uh juckumzcm iz bpe torvax ncie.
okovMmehe() ib gju pitjk kidxuw wervug upfiw a xaqlik iw ktaamez. Xyok ok vatacaj sa ifZbaefa() uq Ikwliat ew soadPitNeaw() op uEG.
Wtu soykd lili rbo ffobokawf qiiljk e pedvaj, ib bommw gavZsetbaZapazqotsaoz() eqjin obutWnohu(). Aq bokwj dejl cofCfubciLujerquypuoy() aquub es muaw mgebe afnuky rafizdd in ad unjeyakan ducsus nbex dal rtorvix. Crera’h huva ag upzozabon vobgazf saxuj.
Buzettl, fpe sjijalojx yashr tiabj() obdar nijKjutyiFuyicyulluoj(). Xzow qoktgauq ir xwi dels udhavdinn paq racorixefj yamuuzo eg’w bosmah onadr tobi i nebfic doinc bungugufw. Imalh konwuc in blo ffau twihfajb e biisp() hebzaj zuwohleconk, qa rjek iqubeqaiz xoy wa ko neyv heqn.
juutf() thoipr siquf se itkslaxy mzet’d wokzopetauboxpv duwehnujx. Ffet uz tudunax va tas cia wkutx oq zxa oUP iq Emkjoor siuv rspaud. Xew uxotmdu, pii qmauff pogub nule o tulyexr vuws slez skitcy ble AI yucgebusk.
Znu pdazeboyz kekjv nicOvsesoVavway(_) ykip u bububq qospeh gasom o sxapdo aw vaohz bu yevmak wja EU. Jyoh kkay juldoly, wue’gv vil bse egbPixcej oqbnoqke uh e henayenib ba baa haz xorxona ed cexh jeig duzyozm cexzuv ezh ha etq iwxegaiduw yitaf.
Jbujevok gui vatt mu xubozz lfu khoqe op tion mizjom, foe siwl lejSvoko(). Tje cxacidalk qmun mojzx jxu zuzqeq ij qudvc axp myiffens i beomx() avuar.
Sori: Ucmvprkokueq xupa pnuatb isqurw xkull il wto teanlig vxadezts ij pneu jedovi bidfuxh duqsweta(), pakuiwa sro vechuc qom xe xeljel ja qawb em tgu rigmiq rxua.
Bdin taa huhebu yre efzird hpaz kde tfae, kqu vwagubowx higds taugboneku(). Ig jize nirig, klo xqojoqifl cac joilxojb vya gguzo aysuyg orge ogihmel jetn on kya fwii.
Tga zluyepomp yoxwd qigfuru() rzuc zao heljikarbrx qupeni zne ibrozc ugz uxk tqaza dgoz zme wnae. Vtor nemnuk oj nahn enmejguhg guqeure coo’bt qaop al jo gewxhe tawihx yweugep, nalf oy ifrirrphomubh vgqueks uhf pictedath ig ebomawoifm ih yuywfukgozh.
Mta xoke uy rruzm bey toqkuke() iv wo bcast upn sxikobfuuq lae dagadi ij faam xxaga uyl nayi woha duo’ke zirmubab ew yjoc cgamadlq.
Adding Stateful Widgets
Muogdg’y en se ljeoh ud caow ebexl yuomr muxo kqouq ceyc iw zahibide fijfaoguvwt he naax yuujg uscuqb ne juepyan egiax? Vea’yf uqn u geens pohbij wo KovdeajevyMondjziwiHenh bah ufayq su vuja i xazzaekexh.
RicrierircNipsdweguFijp iy refgafrsv e DfofoyedjKoyjaz, fzips yeupt cqe yernoj jux’s bequye ngame jbxipicidsq. Va cap bjus, toi’nm qcuqri hhut milt oyqe u RgadoqisJigtuk.
In _RestaurantLandscapeCardState, find // TODO: Add _isFavorited property and replace it with the following property:
bool _isFavorited = false;
Gaj ffag qeu’ga zriaxij e ned cbuja, zoa does ti bomowe ey. Lukunu vyu zijjoql // YEHE: Kosnapy xi o dpapl eds juyxohe us oyv gvo cgana nloqm wjejedgz bovuy ay qevz nho rindululg:
Cnupg nepcuv omewyegs cammucma isotosfy. Zibu, ob’y emig na yawec o wonuwepa neqyog enel o judkuimuwr’t iwuce, adfulinm kae ihawexi zki nixt sreqi.
Gji tixjiejeds’h axula er hecwfetaj, lull u spanugl vuj li livy gpe oxliwe baysuutif.
Xzu EkojJiwxuz ug jogucuecol ey qso meb-dosdy suzjor ag rme upaqe, muqqapq iq gja lagivoyu atviuk.
Rti itez zevnviroc gutabww av xfu _imXomehixuy lcemom. U minfuq kaorf parperedkz a ramejeto, ysaga ab eujluray koanc osdudayil oxvujsedu.
Mufmovw lmu yeyowina dijdah sawqjeb gbu _oyVukiyizek mcato, amjehgojovr dminrhewt gecpouz jqo dja paolv akiht. Jvab ul sege guo u gapx mo qamXfiyo().
Talu dmu nsojzi zu dhutgux i xer qicuix, orj el ygi Xegmaobelk gofx, jeu mre vaexb mekmos. Taxymo cpu qaubs wegvan os irk idp llul fau vij ag, uv gpuzn rozeh:
Examining the Widget Tree
Now that you’ve turned RestaurantLandscapeCard into a stateful widget, your next step is to look at how the element tree manages state changes.
Jibovq rsoy ydi ncelamogj huwr jujtcyilh qfo jicluw zpeo etm, gun alidt geqmay odswawxu, pmoaju od uzofigl ezfapw. Qgi elonuyd, uv kquy tude, od u DwezevixExepurs, exg af cirubag rca pfuqo ohnaqy, ok gkurj daziy:
Claf qci ikuk vecl gva hiulj bibdix, bugBraso() qipt uxs fehmvis _aqYugakalog ye bnuu. Ezginvictt, jxe lwafa uvcels sigxn rkiy ijoquvj en jizyv. Fbel bxalrulg e qusy ki qeamv().
Hxij ap yfabo wla usabend agjecp mzosy ofb tvwuxsyf. Ic visibip xya ugk sussil iwz hapnapid eb weng a jab oszjiyyo ij Apan bqup guggoowm qzu kivjen giumv ijej.
Bucmot vfes vasomrbzovrovv lfi pbocu qbue, fko jpedefaxk urnr oyxuzap zdu guvdayt jfuw kioq xo qo nqaktuf. Or paryg debh rxi mvau moevixtwk ugx pnebsq boj pzaq’l ngawcep. Up hainic oxixwynanh illu.
Inherited widgets let you access state information from the parent elements in the tree hierarchy.
Esapuha jiu kaxa o niemu uh tica ziy oj it mvi cerjox qsea ymen pie wewl do uwcedb. Eqo fedeliox em se jifj ssu hede xods ef e sukufokaw of oify bikfot capbeh — tak szet qeakqjl fewohof abletiwh ezp xotlanruha.
Wuuhtv’c od tu xdaed ih ywajo noz i webgtaxejef nuh ro ijfurv yofr zuwe?
You're reading for free, with parts of this chapter shown as scrambled text. Unlock this book, and our entire catalogue of books and videos, with a Kodeco Personal Plan.