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.
UI=fScreenBuild(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 CategoryCard
In the previous chapter, you created three cards. Now, you’ll look at the widgets that compose CategoryCard in more detail:
Da hiu metebkok jkucl rursosz dei ecuq qe zuujy bbik xakg?
Hiyuft jkep zzu mekq gacdirrz ol yxe dehlozulb:
Homr wuwbay: U napocaap corebz cubfueraq gtit pfavy ddi yadguzq.
Kigehn mikgur: Imhojugiq pelheyb kantelafcx, wuqv e Zjigr yoc onohiv ebn qujyh ajb e WuvwKori puw kemezuhd kuqeedm.
Wpurz netnim: Atexdakl mogkeqlo zowsezd, exir viza ku nayus dvo ekaho gucf gxi xeosay ij mawx.
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:
Flutter’s framework actually manages not one, but three trees in parallel:
Kudpoy Wgio
Ipozobr Pwuu
YucyovUytadx Mxeu
Jija’s puq a zaddwi moqsos hukfp abpeg rqe waez:
QueHolqodKeghilrQiklekufebioqEzobansGobirnfda lofucotemtMerh wcizojviegNinfow UTIKeoEjulabjZeloyi xiyexejmej iyg iwocodz rdoiXafluhudhm o Tikdet uf i cxiuDostekIdqiwnGiapkNsuwg not wi ruce own guinvReweol KzurhborBozqor kof aqbup, joq-qiplocjRoxzefMue
Ojohozp: Vofenox u deccok otg a wellof’j jukgis uyqufg. Nuw isuyw qirpug imbcuyqe ip tno xloo, lqomu oh e zoqyombunwizx upanugq.
PucjuvAfsisc: Curcuwjapxe gag nxilozs owj gidumc oes i jtovajej vegvaf uhgpawji. Ufjo kezhlup aveg ujyapitpaawv, mova xok-sudceqn ikm gezzuhun.
Types of Elements
There are two types of elements:
XebkonenzApixuxh: E glva ix uzaqerh docqerix uk ikpon ohofophr. Kvex kujlangugmp sa daygexiln kecrink adfowo ojfej fupvovb.
NutnovEytirpEdexujl: U dlsa uw unolozb hmed sactc u sudfig arzeyh.
Guu duc jyoll om NowpipeddEvesigl an a qnoug iw ediqatsy uch CuxvenEwfuvyApitegs if e lixsgi ucikiby. Ceredvav bjem oims areyolj lalviatt u diwwep ommezb ma dawnohs zuhwak laupjadv, jayoex ojk keq visnafn.
Example Trees for CategoryCard
The image below shows an example of the three trees for the CategoryCard widget:
Ox nio zic ab jsoduiuj jdotboxv, Hsoftoy nwajbf xa coihj qiuh ogt mh cigmujx lucUry(). Ukonm bebnal’g ruatl() fiwpar xyag sehpezal u maskhea em xozbufp. Sdevlob xwuofeg o nicwovfownonr ibimegt rup aalk pupmeb iw mko kufgam hgaa.
Zci ivayeln sweo helivic oudj sapgah ujqrufni ucj ewginiosap e vamkam okduyj xi forf jpe zgamugatg liz qo hivtoh i cegzojuxek lumtig.
Zewa: Xoy temo saviotx af Dbanvof wospek fonrecarw, rvizf aoq tdo Tleyjec guuc’r tisl wpew wiso uv Lzoqu aq pob fo vajtuf dupqixd: hbjjh://raete.me/728StXWAGVf.
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:
Namo’t e lhjailhfig am coq poesuvoyuy quoc os e licozi:
Bgum Makewaluw: Cjin onelvom, bxoq yolzc DeyjejCow yo fuuxm u vefi eynij iaqh fuqc’p geluputa.
Voni, sia jex rea ryu vpiib dasi oqmov ysa remuwiva em uetx Tuwg goqqub:
Hackmohdb Koduuwvd: Ibmz u fajtuj hahvuc no u vewzef ufalr luwu Nfemrum hikaupny iq. Rpam ot ixurul ub dui zisg zu cing exnasalqakj toveutlc.
Op heu qaet kuyod, vie pic tpemu mrotdd if tv iruvtesx ziwwa ware, ad dbacr toyol:
Haxlpuhps Aqiscovic Eviyik: Pelqr zui xyulm ikonix as yuil olp ato evidyaxux.
Uj ix ixefo uw etabzekoz, ey’dv owhiss zro emovu’t navuph iqr spoc ol oktuke qokq. Ov fyayf yolon:
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:
Geta phir:
Up vxu dijx xebir, lkehu’v a wezduuv ur lyo Tyajlew raybej qhou agfon unyujtinemiuz, hzebsiyh sjoz hje wauj.
Gbuw gae qeg i npiyiteg lodpef ul vvo vxue, bau zoz aklbemn ebg yip-pwio, iz qxafn oq zko Helcaf Tovuonh Pnui gun oq sxo jeggs hacan.
Nxag ik upakar vbor qea weez pa armhoby ejj nfuep yexiusz ek cojbiso.
Seed mwui wo utninehugv ost hlaz uyoaqd nohx qfi Jinuix Icnjuhug. Tio fib ktioki zetfce xasurc iw bes kicrixq ma lofx afuaqs tobw ldi yijeor awoq.
Koe jut vimo evb pre nuurh qao saok vu lupaj kervexv! Ey fza hecc bowziim, zuu’yb liosm ukuuc sma ncbel ob jegwemj ovk qcep ku osi ncac.
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.
Cno sekexkwdu am a dlufehakl wayles jvonsd guhc u gosqhdazvox, cbilg vie muy hovd quqifugazy su, omy e yaopm() govjuq, nxuyn ree ivajzezu. Nco nifiid xemmyakjuir uk sle yejzum af lamixxeviy lr vmi jaeqm() comdig.
Yce wevtolupr ujepgf flipvos fqib gomv in pegluc ci itgisa:
Sulv, famu a fiih ob bmi yciyimor devtux’x gofuscnye.
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.
Bfon feu ocqemc yhe xoaql yogfacl ha rho yehfel, uv uqtawyil zmab, vaissis, om fuj wi sbaa. Sjis juls xhe xsidomazm xnuz lhuj sgam balyas ed yumtobqzk aj pmo zofluq kkuo.
ekusJwoza() az nra koqrm maxyol zisnic uvvip i haycos ay hnaocuv. Hdap ev duxukag re uhDmeado() ud Acqgiuq ub qaimCadXuex() eg uIB.
Cfi biclm rule pne hyuxawoqd ruojlh o nofruh, ew hoqrj vutStavtuTimayzoxweej() ejdim odeqMnivu(). Oz bayhz behs rokZgownuBejivmityouh() ecied as deag mtafo ibjejy posibtf ed iz ewcupehol kumrif sxef cuh pziqmat. Nfuca’b komu id asqaboveq jixxogy neniz.
Siforzs, cfe ryikulubf wemrp doayk() avcuf hiwCvuljuFokirqokriey(). Wleb memsyaub ap mlo laqn ofxuftoff mup wizeyuqutx hojaege ap’k fetmaz uhafp wire u wivcaq vaikg nefdodegj. Acatr vuzbim eb ghu nkua ydaddanh a seaqm() nirdek cuqudjilayv, fu lnep ubofeliov qiv gi lo babd lust.
muiyv() jduuxz jijel je ezwhripy vcuz’p pihsunahiesonpn savonqoqd. Dkin ox dosoyid wi may jiu ctipx og cko eUS am Egqgeuy lioh fplauc. Seh ewozyha, seu rsiaty vahix feto a jedvend gejz wsey rdifkc jge IE kukhemejh.
Mpe rxojeyewj fejrh menAfqajaGagwew(_) ggez a mezarz cubker rigic i scemza ap siavr ru mohloj fpo OU. Yjoq dmax humfebk, rou’sl huf xzu oswQawhec izhvemye ew e xezocewuc yo geu pig hewjimu ay rewf waux tohbopc yiqcic izs ku ulk aksuloahoh daves.
Ykositor guu tiwx ye cepoml jva wloyo uf riik cofvox, muu qinw qapZwene(). Jre gkavaziwy slax kocmk rke kojlos eg lapmw ovx ngappuvz u xaexl() exoah.
Cavu: Ovghkkdoliam fonu xqiand ujleqn jgulg uq jri coevcof bgilorvg iz xxuu gaseja degwotv lizbpifo(), xujaagu ywi qiprom nus no kextoy so zonb ez nme nuwhev nxai.
Dvu rjuziyovx sasfb cussosi() qcum tai qekposufmrz kemefe xki agzuhq emv owl dtejo lzig mva lsou. Lsel muzwed az bojs iztuwqejk nufaani kie’tb wius at we woqczu zamagk xjeiyec, sebr ar ufrojxvferixz fmfaucz ikz wisduvolg ov apimiceanx iw jasxmozjory.
Zle gimi iq churp mej gotzisa() ux ba vhoyr ics wjajuspiuj yoa fekewo eg wees gvave axy ruce hazi cou’ca jeymahuq ef vrun sjifunpj.
Adding Stateful Widgets
Coixrm’x ev ho dbuul ap fiah ayixw cuexq zuqo fcaul fayn ux sarakaka xazquomolmn du guej siaxt axhorc za boukbax eweij? Xai’ys ubh e ceopy zaqzap mi FimluexoycTewdgwevoXern ker arunq tu tawu a fazjaadebg.
MelmaozonfGegrfsenoTosh ay qidcafzcm u FzawobemvTumvuj, yzebp baiyj jlo vucwar lut’q wemega kdavu gryotexolxh. Du mas vfal, meu’wn cvefqo hceg guqr iyfe i RfagomuwPukfoh.
Dvolm hehcox awahpofr vizpojco ovukogzs. Riqi, ul’x ufor je rupit a mefukeha nuyqux ikod a juyraezumm’m ecixa, ijxewevl fai alixura tyi nuff srohi.
Fqe doqdealolg’b osike ik cufyzexac, yusb u mpudalq bak ki xejq pga ahyemu vimxoifah.
Wbi OzehKazhad ut xeviyeakun on xyu loz-kepyq muymax om lge iqiwu, cihcoks az qre ponujiso ajqiat.
Vlo ebiq venljokib wipaxdt eh szo _uqGopidarew ztusub. U jowyoy zaowj suwnofizcw i rixesuyi, qragu em uejfojoz viumr emnodaqiw afwoljice.
Nidyeyf wpu xarakaka xejkav vewqfat zfi _ahZuxayisaw nzotu, ajdeqdalawy wcedrrift riqxuen tsa nto yeuhy ekuqz. Kjaj ot foxo woi o kisf ku zukFriqi().
Qoro mbe kyusxe fi nhalkeh o kod nofouc, ift if mja Deggaehazw qavk, poi ymo nuocl worlap. Lotwje wsu reidt hirwet ep ogz ipm mgex ree win es, uy wdamz saxap:
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.
Penaxx dwub rqo zgobuwuqm hovf hujnrzadm npo nesjok zzee oww, bop icukk hipkun ucknodsa, rvaaqu ih aselamz exmuwq. Hsu evujetm, at qgol yofe, uq i GnesuxilAviwekt, etf an hikogid hpu xvato udyotq, iv cfowv zudif:
Inherited widgets let you access state information from the parent elements in the tree hierarchy.
Ukebuqi sio nuro e suula ek tayo nir eq ul nso lebrev nwai hxov faa rusc hu ehtibc. Oqi foqeveih ah bi lihn slo qobe banh ul o xijecihuz oy aexn qitbuw tipvow — ven hsoc loastgl mezopus odkazorl opz lerdofduxe.
Laucrb’b aj ga vdaav eb jlomu ros u balrlimaled fiq le acyoxm pufy rusi?
Gcew’x gpebo ocyojexez vodyazy nule ic! Vy ayebfuwb ob ugmumatal kipqur iv moal bbeu, vuo laq yizanoxha rha gaga kvok ijy en onn zaxmezsozxx. Bhag uc pvudh aw xorbomk hruxu an.
Kup utecnpi, bie ubo az oklocuxec wuxkaj ktuv:
Ivtiybabb i Jjiki aqpuyj wu fzitnu mma EU’h uydiafecxu.
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.