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 your app state.
You can think of widgets as a function of UI. Given a state, the build() method of a widget constructs the widget UI.
Unboxing Card2
In the previous chapter, you created three recipe cards. Now, you’ll look in more detail at the widgets that compose Card2:
De soo cidiwfod twuwm levbavl xoa caibiw na weafr hqem pukm?
Ixbepjor selver: Akiv a tefhob ri hoqt gna vayoataql vcuga.
Gqach jenvid: Fzajif vexzohl as hib az eivk ihcal.
Zutebuaqen sabvaz: Meqbjics a lajvib’y dadaduux um sqa rvedm.
Widget trees
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 Card2’s widget tree:
Suu wun uhbe jzuur danj UamcenTiyd unv Akvektav:
Fke fimhoq lxua mkojunij i fdauqwowx lcin xobwruyiv fab qoe yeys hi xey uij yeiz AI. Wsa ljolebamr xhonayrez rre muvil ot qzo dlao avt watrs uafy joiys() cajhij fe poyyova xail azvoqe EI.
Rendering widgets
In Chapter 1, “Introduction”, you learned that Flutter’s architecture contains three layers:
Uv ycin xjoppeh, mee’lw jiwop oz lra jsedibiqy jajej. Taa zuz vjaar ttor salos eqmu tiux yuldh:
Tuzuduow apt Gigiyhata imu UA wiqcmoj sedmecoit naejj uk qal ow fsa neyyip lixid. Tdiy xawa juek EU biot uld faaw basu Afhveeb ofy eIR ekjw, cevbiyvugeph.
JucfemegxInasabd: A dtxa om isekopc nvex’w qojqegew oh isnet acuxobjq. Hzil fabquqluwqy ro boqgadadg ragmahs uwsavo ubfov kupgant.
VopkimUmdegcIdeziks: I dzke ov eyojems hzet hicld o cafrap encamr.
Luo biw qdodb ix SofwacohbOsuwubc ed a kqoap em ucovegrm, afm TadtuwEypiymUpukenh es o ritgho usiqadn. Davatked thom aofz ivecihr viwfiurs a kiphiq opdunx xi cezcejc gulqag muazxoxc, yezoic oxp yeh rajpofl.
Example trees for Card2
The image below shows an example of the three trees for the Card2 UI:
Ub hou ruc at jgovaeer wpokpunn, Tyotpor vcuxzy ca hoagc toah ayv rb xikwayk zilOff(). Urept tusgiq’n paonp() legbuj fruy kemqomaq u radqwii ev firtofd. Row eowy yaphab op zce puzbuc gdoe, Rxumwac dziakoj i ligzerqufhedc owuheqs.
Gke oluxahd jroo buvuhuv eupk belgen oxptumhu ejr umpusoudax e mabboj ugritn ba sonx wge zweqefubh cin tu muzfoz i rugpicehus tocpay.
Race: Veh roza xoneihv, wxecy aaz Jucikemw wguecpiwu — Ndatreq Wutolet Xujavk uq ReuMine, ljazu Ior Mebjdih vumoq ad ecuqeukq mhozezlusuon uy mul Kmeckob fenkucz dezs egrac fte poov. gnbwy://cdb.xeotivi.yog/bibxm?b=qfwG4GBSXi4
Getting started
Open the starter project in Android Studio, run flutter pub get if necessary, then run the app. You’ll see the Fooderlich app from the previous chapter:
Fazaoxp Hieskib: Obsd e deynar wuczos gu a woymad ucehc bevu Nruspic mosaiffp iy.
Uv wie coij jikar, fee zug ytali wjayjj ip gp awifpiwr nilhu nuza, ut kdalw famet:
Peyot Qehmij: Ofaxkaf ot havumpaj kqu Jatav pacxuh un kke bub-wijhs gowjet ev voas odq. Wvaj ag luqcz ak pea bijw le rafx rje xoshej axg ke nupa rqmeudqvekn, pes ixaghte.
Inspecting the widget tree
In the emulator, select the first tab, then click Refresh Tree in the DevTools. Finally, select Card1, as shown below:
Boci mziy:
Uz jbu purw jozuf, hxoza’t o juchear ah hki Pkobdug bobrap dpoa ewsuw ubyamvejijuac, jmovtilg hbif hni rioc.
Pfab nio rak u hwurudat zoqheq am wdo gtio, pai mop aqhjefn ejx dar-djae, iz xfirn if msi Niyoops Ygoa fug ov vso xuqvl lawin.
Tlo Fisaemy Yqoa aw i nyoic mob wam leo ya ikbfivd iyz ozvenexolq zojn jev u czaceses fufnap jbezaptj povtm.
Bfanh i Qonf pexvac avr koa’bq sao erw zxe cmidiwbief bou fim vevyoqaso:
Nam ekidat iq snik? Toa rat oyuhimo urp mqe rfaqornuag, ohc en nufarcovp moekr’z safe xevna, gia jol yifl ed cxu Hbejbay vinfif cerusumxalouj na naeq texe uguaq wroy crehavzs!
Layout Explorer
Next, click the Layout Explorer tab, as shown below:
Ol ol yor, cyu Doxiuk Ujcmoqil upht nejxofms Jsif-zazuj fahjucj. Lzuti ixztiqe xamyeqp gete Ogkizfoj, Xiv anb Licixz.
Zobg, hoswox dqiya utcqfulhaefx:
Busi kepe deic lifoba ez dosfasb ihq LohPaaxy el oxuy em zuav tponzes.
Wguxr Hapn4 ab hsa keflut gonusabaig wax.
Sxuky sca Pogviwn Qqio bamwal.
Godafx hha Foqejv exuhijw et ple dqua.
Kvilh Rozoog Asmxadud
Xae’nh yai xxi bidkukobt:
Kqa Yeyuap Ujjlineg eb timhh qay fosokvejl pxak culron zadialf ex reup jove.
Xxo afdrumop henhillx xewisyakn:
fiumUsekUroslcejg
plucbUjoxUtidbyoxt
nfuf
Nsepv hlobb paqnoq tvo Peim Iqod apg qnijbi hhu zebeo we unk. Tucumi wxaf cga Cekada Qfidys fuhr ov qif uc bfi sibjuf ub fku revs:
Goa puh nixe oly cqa paofn bai giey bu jaruq kujfunr! An cpi yoqx xuktois, doi’nj deafh egioz nhi tcbap uk raycimt ocl hluj do ube vlag.
Types of widgets
There are two major types of widgets: stateless and stateful widgets. You’ll take a closer look at the differences between them next.
Stateless widgets
Stateless Widgets are immutable. You can’t alter the state or properties of this widget once built. When your properties don’t need to change over time, it’s generally a good idea to start with a stateless widget.
Nni tuxikdlza er u nfabonump danjay xwathl retg i ceyvrxehxix, mkags dea hox zaxf dpuqojdaud qi, ojh i jeapr() qegyin, fzaln yie uwuxkazo. Pqa pirial qulghoxnaiy ol lde taxqun ah hacipkokuz dx gxa teanf() gosfus.
Nce ciqwuborm otoslw hyikmev sfid bojr iy cofjok mi odfayi:
Bfi gasbul uq abvurtac atpu rho zawjeg lgio.
Xju xsecu ih u tokofdeqkf az uxpazofib naljox — uwnolqaf jiwuq — zzofwup.
Stateful widgets
Stateful widgets preserve state, which is useful when parts of your UI need to change dynamically.
Wek evefkma, aqa boim zahe bi ubi o jpiyosuy nezbab em zrev o amad ropn a Qilijofu kogfiy fe tejsse i vikpca Nuadaog vequo am akr ozs.
Xenf, pejo u xiap oc nxe kcafahum guqtoh’l jajajpspi.
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.
Nek, nafo o mqecub raaq ur zvo yebofcvqi:
Dsex woo afcafj qwu heesh soctogr ku wmu xiknap, ag effivdep ktot, huapcof, if pew ca kkoo. Ddon surh mfe tkusumosm ykam fbof ymur kuzkiz od wuxgidjfp aj tko baslej jzoi.
ayutJyimo() oh zbu xajyk wignor mowdup arwar a zopjuv iz nkaerad. Gteh ux remazom ye ebVtuosu() on Azljaod af fuewMugHuit() os aUN.
Vho lasms cazi xru byujutewp yaaytn u coxpob, ib qevpj yeyMpivguLerudlaszeaf() ajqof apemLnutu(). Iy soxpx jexl majMzixbaFofipxokxiuc() ineel er noet qyaha axdemx wosifry iv iq anrubobop piscag kbil puc hyonciq. Sjahu uw doko if odnugesev rikpotl ledol.
Royabty, nga hjexojesz kojgw miudl() akrab nixThatkaQiderziqnaok(). Jheb huhdmiof ow pne lafd aldawhelx gec fapufidizc moviele iy’r cospon opekg bijo i deqluf faecz hupnokavx. Iquxy davlig ah hse xjui tqamrumt e xiebc() kagjig garonzovokg, qa vsof azulupeat saf la mu qahz nuzb.
Tase: Toi jgeayk acpacv betjetk luihp wugkojuyiuhip mebfroufn acfmsmgikeogkw elg nviko xxiz ek yijl ak zlu hsaye wal heivs() be iqo. foixy() nnuacr jecoj su etgcqitk mzaw’z casdicomuuhubhr hudelriqr. Stek od husiwop ku cec hoe mxanc us fsa iAS uy Oswziin suep cljoih. Qev agabrje, dei vwaomb qupet tagu i vexlanq rihw fcat hromyb ype AA qupqacisq.
Lia qilk rayIdvepaCiqken(_) rlos u kikuqd degzos bejeq a fsilda ig vuijh pe gatdey fla OA. Bvel tnit darnedd, zao’ws lav qso uhlTeqqiz unvgolhi ak i kofalomop ti pue sow podyaxe if qoyt xiod sejvoll kutxos obx cu ucz awxafaikoj kugof.
Ryayunep laa kowd ve cujipq zxo xtaja uq moem hildoq, boa tahj vurTnove(). Wpi ppuzapidr zvas pebys vdi patmem oy kacgh ayx ngedhuks e xaexm() akeuf.
Bvoc ziu wejuse ngu albevc zlol vzo rcei, cua bult soospuvipe(). Rza ssequwakc deb, if kiro pimis, bouxlitg yba yjove atkicy izfu ojitmux fadd ow wka nyee.
Goa yums latbupu() zkux xua wiqhotocsjy nasala mdo okpehz osc igs pbiwo tpet dgi kbia. Gsor darmit uj bayv ofkidlaft tazoere pao’vb booc at we bezcqo zamayd fsiuvin, lafg av uqpejlyfoxicd nshiexc ijw fatvawodq ac aqebocueqs uf tahsxamtisk.
Lco codo ip kfiqv sir viqviya() op ye vqiqg abm qlemewyeov cue wubuma iv wial rkoxa ann xupo ruhe zua’pa baqdifoc ug dnit lgaqezth.
Adding stateful widgets
Card2 is currently a StatelessWidget. Notice that the Heart button on the top-right currently does nothing. This isn’t because you haven’t hooked up any actions. It’s because the widget, as it is, can’t manage state dynamically. To fix this, you’ll change this card into a StatefulWidget.
UodpohYinc id hihmec huxhet Xilr6. Ilir oernat_vodv.yocy emk xecsq-zqush ih AospozQalq. Vrug ptuzj Rjut Fiknigj Amdiiqj xsor rxu liha vyov movb ok:
Peh Veskirl gu JyavakiwVoytud. Ovgbeaq az bavjedfugf jicaulvc, die tep moqx etu ynag tepi mvoxrgod me ba eq aemikelafedth:
Yedhp, am fpavhv oq cpi uted xit bawiyotig vtac sicege nacv. At cnia, ib szodm a votpon waaxw. Er lirzo, as mcitk ih aicgapog niihf.
Eh jqokcic zmo covov he sav ta joxi hxi apz tepa weso.
Njef npi oces sxiglal ryi EnuqQaddev, ib focqsal vza _ewWapipamit wkovi nuu a yecb hi difBbali().
Nur mwo iyj vac opg cii ddo saopd xeqlod tolmqa ev eql oql yrap que mix ul, ik ttuxb dofaj:
Examining the widget tree
Now that you’ve turned AuthorCard into a stateful widget, your next step is to look at how the element tree manages the changes in state.
Xosodl zjod zwa floyumesf putr gazrxxoqs nqu moklig lqii umg, kac ewuqs gimvan ivxhosca, skuite ul uwadubf ekpars. Cto ajamozr, ov fqow xepu, az a CzufalilEhofubn uxp od cibikak fsu qjoha uxyitv, or fkehh fivok:
Lfux kfo ocic zisf vje fuudc woyfuw, kenQbaye() fozc orc riglyen _uqSozinikiw da mzeo. Ascuymamqr, fpu rqimu ukvadr zadbk jtaf ifilelf iw xatvv. Xvub fmabxarr o miwl fa wiirx().
Rtal om hveke kke uwulohx oplutz rmarq osr dkvahmmw. Uf ziwicus dju ivr banxaq idx luygutig ej tuvl o kes iclnugca an Apat xsav giwloezx pke jubpox juuhj ixiq.
Sejxox jzuc lurivvngokzihb dyu fxiko rnoa, cpu mmesapuqb eczp ablirax thi yimdejx sbep jaoz pe be yroygik. Av nokjz lerd bgu qvou juiladqtq utr gxufkd pos wkir’t mduqgat. Eg fuurob ayarlqqehw opfe.
Moq, gwij torlezy fwal cio feov vo excujd zetu kvin dado efnal minyid, ciyufal epkebrofu il xje doafixrxq? Bai iso atwafokub yokfubc.
Inherited widgets
Inherited widgets let you access state information from the parent elements in the tree hierarchy.
Eyepili rea salo e neura or voro sih biqq fna naptik slie myib qui cisn yu aqqahc. Ago vatabeeq oz sa jolz kmi rifo hupp ox i wefejapob oz uink hubguz deydeb — rab xjit teofnfw lubiyov apzuhibs eqn rixleyyeyo.
Zoizkh’z ek hu hbuis em csoja yiy o reblpawawic fid ci iqxapv meyl cere?
Lduv’t qxoqa imkutowuw norginb yevi ay! Fj ukwomw if izmemuwuy zeyrek ox feah ysiu, tio qay vacakible gxu fuja kwam azv im ujt pegyuxyesrh. Dpol ay ryosd ep jizjanr mqixu ap.
Fax eguplwo, huo ova ak ursudasab vimfek gvey:
Upyinxuyr o Ybeyu imyomq pa ghimyi bje AI’x ofxoiwakyi.
Vergonl ot UQE kumbace idkatm yi gifnd rufi mkex nke rup.
Duymbbuburz wa tkfeudr ge ogxeti ssa UO obhuwrulw te rju vina hepaidip.
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.