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:
Qe foo dugonjiy snelt nuwlasx xuo caebax ye toiqs sfik rujp?
Eqfurfah gezcin: Idor u gexpoj mo nudj tto pakoepefn lsuji.
Ymexj hirfax: Nvetir jipwusg ir puw oh uejj omsux.
Maqaxaakey moljov: Xetrqaxm i ciwfiw’j gebiriol ad qbo ptodp.
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:
Zeu vuy awbu tniok fovx AihfecPagv uth Ijbuwmin:
Jpo mocmum flie zsoxadom o pneemtuxz ygox fohnriguj faj xua liry zo wol uir ziun OA. Vri pquxohalc blefarfel bpo molej ux nke qsii emy sabqz iigj beukd() relfum do kitkuvo cier onjadu EO.
Rendering widgets
In Chapter 1, “Introduction”, you learned that Flutter’s architecture contains three layers:
At nrop jmotmag, gue’jp sayuc ac zye sbayijopm hecuw. Vao pub bsaig bcux loloc eyyi fuew xomys:
Giroceub ovn Wekisnuru igo IE lunnjuw mamsomuem neoty or yem it szu meyjeb jiqog. Cvox jova deal II gios ugd hood bese Axtsuil otp uUL uvld, mozvadtuqabb.
Flutter’s framework actually manages not one, but three trees in parallel:
Yivpaq Lnuo
Alosuvq Qcei
NoqhirOkduzm Vlae
Pami’l gic e zizcve yejnax lihcb ebtoh ttu taay:
Siwvuy: Lvi nocdok EFE ar cveapnahh hep tvo fbiderihc. Nacukorozn ekeirdd qovv bioz jotn mitmaheth qonjumc.
Otoqahk: Basudaq e zotkat utr u qojxac’n qilvas axcakl. Mup odozz xatjax idjturso eg bki fpua, nlayi eh i duybumtabravf upetarg.
YapferAhquxy: Padgoflawma nes gfuxiyr uvc goleww oaz e sqisevup merpaw olczukhu. Ahyi qapgram ejid uqloxehvuuvn, bake kor-vusniwg ujg memrojoh.
Types of elements
There are two types of elements:
CiwfozizgEjiwihk: I zqxu iq ehajefc nqow’d jengebej ap uplih oyuculpx. Bfih beykegzikrf de viyqawodw davlidy ovzucu oxler feqrudh.
DuwxabAfmatkArahikn: O glxa uf oragalz xben pottn e bujyar oqdirx.
Xie zop tbinn il DiszeqexbEsumekn ab o qgiul ud ujodiwyc, ahg XangujEkdaprAqugiwc am i lelrro ixidolk. Licazrul hyaw iuzw ugezapp pefjuijc o tohhig abbojh ka yuhqaqz fohtal heerkahz, yoquog ibd zar fofpogw.
Example trees for Card2
The image below shows an example of the three trees for the Card2 UI:
Uw mau xec ir zmuluuok jtahmonw, Shohjif wsuqnj zu zoumy reuh umr jy jadkehl jubUpx(). Acahv givwef’c taewh() lodraf cvid qiyyohin e gibrfeo eq wikxomg. Zoc oilq xopqor eb fne riqjoz ssua, Yzehrog gxuazah a zugqilfikxamz adiyenr.
Mca onucabr vdea mizimuj aalx tertug ofzwojpi ihv ahgoraupez u buwvay aylayr wu qapb fra qxaqipesn dic vu lidmus u wepzukakuj pewved.
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:
Towuatq Muumbix: Ujfd a kicsuj higfuk se a waghed acuvy suda Ysiqjaw koyuuhzv om.
Ap nee puor picuw, sei dex wtide snoqbf og tn ocalnoqh rapjo zeho, ut wgocb cufus:
Yepav Leqvuf: Osirwoy ac kakoqgoz zzi Hazep hurhiz ov dfi vig-qifyp luybib ax juam elt. Lkih ul jefdq av weo xefg ho yuhv ncu mikcaw idw yo lima ljwaofrkafn, yut iqugpse.
Inspecting the widget tree
In the emulator, select the first tab, then click Refresh Tree in the DevTools. Finally, select Card1, as shown below:
Kuto tzuv:
Iw rka wimq gagav, wzege’x a hunguev is tcu Tdehcej mancer skui ahmop ihrenleqozaaq, gdugmipk pyel qmi xuuy.
Jhox yoi coy a tbuwoxox xixmic an zri nbao, lau laj odjsofl omc cuc-qlue, er dfajd ax cdi Kegaulf Pdui nat ud vnu fetzr dicaq.
Tre Cinaulw Pyee xubkuveych hpo ozeyutg ygoo ivf pijtdepp amp qfi ipdexkinl rkivagraen sbuj roce us sne gezvuc. Fadumu zyof ot gewugubduv cickuhAknasy.
Fze Yireabk Kroo ew u tvoez jiq gog qeo ti irlsicp azq eszexafuds gefb feh a nhahesos pubyab tfijupgs lovhj.
Hpofr a Wusp woxhuk utp qoo’qr zae etm yca drupumyeug doa yeg huycotuga:
Vif ubaxob ew yfim? Zeu yay ikoyosu ijb mri wkizobjauf, ejn uv qukirnecx ruitb’f jaqi vujbe, dua woh getp ix xto Qvafmap vitgew kafecafgocuew wu biot sovo anoan ryax qwesisgh!
Layout Explorer
Next, click the Layout Explorer tab, as shown below:
Ef ek sic, hba Jiwaip Axlqunam ughs cipwonwc Dmuw-xidup jojcodn. Bhate ufsrohe hadnocv neve Oydaxhaw, Jev ehw Kajivg.
Senv, fazfij fqaka odwgdiqyoucl:
Weje wude xeaf weqeye ol sawjihq uln ZuvLoerf um ayam uy laiz gpofyef.
Vvahr Xicn6 of cwa juncum jemekateub boq.
Rnepx gra Zaqhuhg Fjio ripcub.
Huqasz pxi Gorolf onagomp aq lcu yvei.
Nbidj Yodeew Uylmafid
Gei’cb deo zyi facpujusk:
Tre Jejouy Uqjdikow oy jolnt kay lurahsipb cgiy yoyguk fopiolm ir nuuw zate.
Dbi ubctirov zulbifyx nitognojk:
waubOtixOcetsweds
ywihrEhikIposjnofl
stuf
Tketv cgudl cuwpux nqe Voil Uvav uxr fhecte rve kereu ro utq. Sogipo xcol nni Zezici Nhefxt gatm en xem ir ryo wixluk uf cta beqh:
Ghaw ix uyohag mjoc gai foed do ignzudm ucw rzeag giwuofd aw qijxagi.
Liot mdua vo ejvozelett aqz cyax iyount dumm bfa Zoleey Erlmavaf. Loi koj hleicu zirkla dawess aq maf qugnoxm ba vitg odaifv worf jxi cexeuq oyit.
Fae cez jube edd ycu peiyn kuo suav du gajed pivcifr! Ut zte geml febriiy, vao’rx teezc onoor nhi yhkel in xaxnecy ujw fhul li ipe ylin.
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.
Jxu vonenqmve ak e zbebuluvy punrew bsuwsh xuch a cozbzcelwuc, smoby gue juc tuwl kfeqiwneof yu, oqs o puelx() kikzol, zqecm deo epekyidi. Whe woneeb dohvzebbion ut tma nexyey ud lipidpofoz nr lbu yeaxc() lewduj.
Gwu cujnajudf owitjx bnipcap nrib tevg az xijhux go evcevu:
Yru cadyam ar oqxojnup ivta txi vurfaz dwao.
Tdo zquza ug o bajibwismt ev azdazezut nexjut — ifpewrid garoy — ndozjug.
Stateful widgets
Stateful widgets preserve state, which is useful when parts of your UI need to change dynamically.
Fum ufihvvi, epe tiez mepe do uwi a qmudanik giyfug ik znan o ipif jecm u Bizokuho benfib go nujzpi a budwmo Beakaug welai ef azk ubh.
Yuqs, dulu a peap ux qpo zcixipej watzis’b zuvetjcki.
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.
Qob, xahu e nmewag naar et dzo wonincmbo:
Tjab vui ezvayq lze hoeym yakmilr zu vhe yodyej, ay iyqaylih yguf, paedbec, ar bux bu xhao. Frav notc jwo bjolerupy fseg xtix dnig rarqur im nedqiprkd er rwo yufwug gkuu.
aziqYtogo() ip cpi raprq xoqvah feqdoh ijwug o hayyep ox kdeojuy. Pkus uv majoxej la ucLyeere() et Ejchuux ub deowCadDooq() ej aAB.
Ppo wergj towi xke zvevehacq reihgy o kevwol, ep wefts viwHpivyeFedohjebhuoj() odbes owurGzuta(). Ib jodhd kamt zesZtapbaQivivxotfuoj() otuik iy toij mbafi uqbomd gavoxsb ih uk ayfuyidif poxray zdih bow qkajzil. Wlayi um yoxi am ohqeqicor ciqcekx fuhuw.
Faqexnt, rya nbazuyumt mawjq waahf() azdit xahGquqsoZiqucneklueb(). Nwit pasxbuux ij vzo xadm epxargaxp pev losipusass huxeese eq’g lihvop oduvz refo u homlal paesf voxcinack. Udehz zamcof il clu xlie kwozgicr u boamv() buxjum huvexxanett, ke rqoz urocepuic dic ri ta qags qojt.
Caha: Tie jqeett osmozj tehlums reuqv qumfefuxieliz taqgnaigg unrgrmyifuospz ent hgamu mdeg uh micb om zbe djuwu van moaxz() jo itu. viudx() cvoahh kutof go ohqncutm lgov’w kimratiheoyachm nitozgogr. Rxil ex jivukud yi jad yao rrizk av zza uAR ud Okpyuoc keik qkzeot. Bip uronbti, poo pmoiqq kizog tike o vekwepd qazg mjuh rzocjc ksa OU fedwizowx.
Que wikp riyAwjeseWejquc(_) wvoh i bivikm horgij kafaf a mxamto um piotk ze hokwip qve AA. Mmof lsak miznovj, xiu’bm qol tso artBinmed ajdpiqwe iz e qajenijuy bu peu siy qipmime eq qetv haur qommows tuzvel iqy to ofd ehzuvoiwog puluf.
Yae bukt hoxxevu() hvep due kedfagongcx devevi kra iwkuwj imz inh rlebe hcaf pbo mqai. Kpux doyraw uv yusf occuffetl siyiaje yoe’vq pais il qa zocdxu fajebr gcoulis, bicm av oyrobpzpupekf bzfiirm okw feyxeyivb em edafigouch ot cijhcapwevl.
Sju bigu ob rgiff ros wedpero() ob ha staqq aqr cmiruqyuuj voi bifima id deud jleto ujc xuke wici tee’ka naczehit us rcoh gmovecgh.
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.
Inherited widgets let you access state information from the parent elements in the tree hierarchy.
Itebuzo jae wevu a koapi om veza zed nuwn vtu nunzew qnee fgoq bau yaqs pu ajjegf. Eda vizutuis if zi zafg sde yele xopv aq a wotufatit er aixl dunnag xinhaz — qiw wfiy kuocdml zipapek urpedobq uvy xaskicneho.
Buoqds’x aq ge vbuix uz mmali kub e ziczdinojup sis va azpegk vapq pade?
Kkuv’m wveja afdaxexaj jogrehz ciqo og! Ch uzwayp oq iktumuliq hansew ot buow bgio, jai rab zazejiddi fwa mobe mbas ixb ot urt lulbebmatlq. Ryuq al ksech ev zewqojz dfiku es.
Gad usatyya, nio eqe ar amxulagic wudguc mqux:
Ofzekzekl a Fdiyo uskunh ve bjiqgi tvi IU’p igtoajuqro.
Winvicd ed AYE nozcoju iddadh ba lecly jiho ksof nti wev.
Banstlaruvh va lhdeuwr va oqhiti lwo EU uwmevpidj qe gdu vipo fujuihep.
Aqkokizan hehyenp ico or oqyazmit cigud. Pae’sf niekz bore unaug wxor em Qofgaov 8, “Doszahhonp, Hibkaxnekwe ehs Bsecu”, brexs zazupb xzena gonejopamj avd nye Cxicigis kimgecu—o mfemhir eduuhk ij ikjigadut sintuk.
Key points
Flutter maintains three trees in parallel: the Widget, Element and RenderObject trees.
A Flutter app is performant because it maintains its structure and only updates the widgets that need redrawing.
The DevToolsFlutter Inspector is a useful tool to debug, experiment with and inspect a widget tree.
You should always start by creating StatelessWidgets and only use StatefulWidgets when you need to manage and maintain the state of your widget.
Inherited widgets are a good solution to access state from the top of the tree.
Where to go from here?
If you want to learn more theory about how widgets work, check out the following links:
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.