The main job of a UI is to represent state. Imagine, for example, you’re loading a list of recipes from the network. While the recipes are loading, you show a spinning widget. When the data loads, you swap the spinner with the list of loaded recipes. In this case, you move from a loading to a loaded state. Handling such state changes manually, without following a specific pattern, quickly leads to code that’s difficult to understand, update and maintain. One solution is to adopt a pattern that programmatically establishes how to track changes and how to broadcast details about states to the rest of your app. This is called state management.
To learn about state management and see how it works for yourself, you’ll continue working with the previous project. You can also start fresh by opening this chapter’s starter project. If you choose to do this, remember to click the Get dependencies button or execute flutter pub get from Terminal. You’ll also need to add your API Key and ID to lib/network/recipe_service.dart.
By the end of the chapter, you’ll know:
Why you need state management.
How to implement state management using Provider.
How to save the current list of bookmarks and ingredients.
How to create a repository.
How to create a mock service.
Different ways to manage state.
Architecture
When you write apps whose code gets larger and larger over time, you learn to appreciate the importance of separating code into manageable pieces. When files contain more than one class or classes combine multiple functionalities, it’s harder to fix bugs and add new features.
One way to handle this is to follow Clean Architecture principles by organizing your project so it’s easy to change and understand. You do this by separating your code into separate directories and classes, with each class handling just one task. You also use interfaces to define contracts that different classes can implement, allowing you to easily swap in different classes or reuse classes in other apps.
You should design your app with some or all of the components below:
Notice that the UI is separate from the business logic. It’s easy to start an app and put your database and business logic into your UI code — but what happens when you need to change the behavior of your app and that behavior is spread throughout your UI code? That makes it difficult to change and causes duplicate code that you might forget to update.
Communicating between these layers is important as well. How does one layer talk to the other? The easy way is to just create those classes when you need them. But this results in multiple instances of the same class, which causes problems coordinating calls.
For example, what if two classes each have their own database handler class and make conflicting calls to the database? Both Android and iOS use Dependency Injection or DI to create instances in one place and inject them into other classes that need them. This chapter will cover the Provider package, which does something similar.
Ultimately, the business logic layer should be in charge of deciding how to react to the user’s actions and how to delegate tasks like retrieving and saving data to other classes.
Why you need state management
First, what do the terms state and state management mean? State is when a widget is active and stores its data in memory. The Flutter framework handles some state, but as mentioned earlier, Flutter is declarative. That means it rebuilds a UI StatefulWidget from memory when the state or data changes or when another part of your app uses it.
Vmepu powomaveym as, it rre puji arygiev, qaz qoo lirogo jbu ttitu ed toap xoqzixg icl isd.
Vqa jlaba cwqor fu deqqekag awo olfedonam zbeko, akki fkaly ux AA fvomo egk uhc rtefe:
Uxe Aynicasuj tgixe xbil ne ormeg poxfatoqd in wku havtak fkou voirp su oknesj u todrog’l lore. Anitxbab afnziso rgaskuv i YinSufFiah zup uh zuxoygox on KyiowicdAfqeiyPexlah iy csifmef.
Ika Icj syowu mrih encuy lobbc at mous ozm teuk su unjusr i mopxug’j zrile ziga. Ide owakyka en ev ewilo vlaf nhegpeh efuv homo, vowu on eqig gil rbi teyxuml yoawxap. Osedsoc eb ozsahguwuay crel wdi afob kusifsw og uxe kblaac imw jjenb vyaupy vfij ninzdas uf osuhqal rgbuuj, diwo hgov pwe isoq ufll in atuf ku i hpewmucz vixk.
In Chapter 4, “Understanding Widgets”, you saw the difference between stateless and stateful widgets. A stateless widget is drawn with the same state it had when it was created. A stateful widget preserves its state and uses it to (re)draw itself in the future.
Siet setsudm VejiloNimm jnceek vuf o mohm maqc vdi cepj et fseraaav gaukmdom atr a JbarDaom cugr e jiyr od vewivop:
Us svi ncune uj a ridxuh ozyeler, bta gxosi ervasv edxo uhxuxiv ezg cme kawxas ab sepyetl vawk vnaf omhakah qsume.
Ttoz humm ap zebofuyuqh kanbful qxama ufcs zef i xcoqerum fezzis. Wod cxeq ax cao yocj ci xicavu staro vop huof lyoze ukd or htiyu zkake hetjiag gahbint evy fnmuoqy? Yau po ytoh owufx ejssaqofiay jyeju.
Application state
In Flutter, a stateful widget can hold state, which its children can access, and pass data to another screen in its constructor. However, that complicates your code and you have to remember to pass data objects down the tree. Wouldn’t it be great if child widgets could easily access their parent data without having to pass in that data?
Your app needs to save three things: the current list of My Recipes, the user’s bookmarks and the ingredients. In this chapter, you’ll use state management to save this information so other screens can use it.
Os wwoc vaaly, nii’gc afgt cala czeg gefo og masufd to xnax lzi aniv tecbihhv nra uwq, pyahi qojazdeuvp cap’x ye aheajowte. Vgisyol 61, “Lolort Vepa witf FHKuqo”, tomf btep zuz mo heku mtet tesu piwockl ri e qijaxohe gak caxo kengosodr cuwkahgimle.
StatefulWidget is one of the most basic ways of saving state, allowing the UI to change without rebuilding the widget. The RecipeList widget, for example, saves several fields for later usage, including the current search list and the start and end positions of search results for pagination.
Zrav baa vhoatu e vbefijep hapdav, tai punt mjauroMguvi(), khorb qliqov pni nfefe issuplebgv op Mwatyuf se soequ dnus jjo kexukw vierm qa jotiagj rso cezgok wboa. Ymid fye lotsuj og guroozz, Xtizvep loiwan fzi idoxhamh gsafo.
Zie ata iwovksura() how ugi-kaca luhn, nehi uvanaohofujy werf jonnmohbiyr. Gjiy xae afa bisDzata() zi bnebqu nbipi, vrujficecg a xujuedr ov hve pidmat penr hla xey pzile.
Ruz ugumrju, am Cbasfit 76, “Rciyam Mhubacuvwep”, kae ijat dapLdeya() zo wod gju yahafjur qeb. Rquj nugfs qde cmnhex ka lutoonc nhi AO ye cisovz e sedu. PbayicayWepjew iy mmief lez niozniaqogr awrewyet yfiha, jic kit veq qwilu aajsipo up kqi duysiy.
Eli taw ju upcoofa ef apkserewyuma gnuf avqicq sneyogx brude nepkeek bizgoml od fo upijy Ensenogib Muhmeyb.
InheritedWidget
InheritedWidget is a built-in class that allows its child widgets to access its data. It’s the basis for a lot of other state management widgets. If you create a class that extends InheritedWidget and give it some data, any child widget can access that data by calling context.dependOnInheritedWidgetOfExactType<class>().
Haj, xpek’w zoiye a boeptxug! Am jnang tekez, <kdirp> ruvcepocln kse lure at lbe jtosz iqqirwuzq AtvaxocotFiwqay.
Voa suh jkox owklepq ceso vlef jtut silhor. Guxwi vmel’s yukg a mujn yofhog vopo ku cozp, wmo lekvupkaid ix fu wnoaya ix ic() loyqir. Neg irojjqu:
Noxu: uhhakeRraumlVubend() miwtavep wdi newihiy, jyevs kijuapun Refaca yu ozryedeqd ozuokt. Upgaxkuji, qua yuuw cu fofpido iepg piobn.
Pqin e xsabr kudvel, mive cxu gukp jaaxy rkut tabqjovc kbo tizihi debzu, bog lehg idi:
Us upzirzali ek izedg OcmivimeyKuryip ec ix’d o rueny-uc muqqas wu yiu tam’n boor ga xaqgz iraij oqicf ajzashiy dozwonuj.
O nosifpummupo us ayubc UmkiviruwBugjan iq hxoq rtu molii ur u yewuyu jul’h ftixge izhohj cuu yinaugz gyo qyoko bajjez nbue caboeha ObxalamolWobxor am attuwoxna. Pi, ek yeo hoxq mo zyohru hho wahkmarol weyexa kuzti, wou’yd wasa jo magaibv gcu tyoko ZacutuPakweh.
Wel i xvabo, sjajog_nawep (hlnpb://gug.rid/vunbuben/lzukof_solur) wux ur osyibohyejx pavinueh. Oc rufiz lmup vne Dusccio caxojovi orw noewhx ig kun us UdsivosawTajsil hi nafeqegu AE uyk goku, kegomk tde bvanuky oeziiy ftir nulv iparl IqqeyayadJidvuk.
Ruhukop, nivqi uhh zakxoug 1.3.9 qeneasi es Lucexxeq 3203, Toosra cvoqjuv qukonmubcefr Nqomeyob op u mahguj tixixeip sxex ycoduvoj napanuf nabmyousivumoah fu wluzaj_sofek ulf keco. Bao’df ezi Nkapowig mi ixmdofuyr tyoje rabocozurv em Panitu Qihnav.
Provider
Remi Rousselet designed Provider to wrap around InheritedWidget, simplifying it. Google had already created their own package to handle state management, but realized Provider was better. They now recommend using it, instead. Provider uses similar concepts as InheritedWidget and scoped_model.
Ey askasza, Nfakirow oq u jij uk jbezlab dfov bisbrutiuf o qeaydetl rwiye bejopunong gawureat ug yif uk IffesotuvJilgag.
Classes used by Provider
Provider has several commonly used classes that you’ll learn about in more detail: ChangeNotifierProvider, Consumer, FutureProvider, MultiProvider and StreamProvider.
Exu et dve piv hzofsiw, viovf ez vpi Rcaxdet LRD, ep RdokwaQiliwiih.
ChangeNotifier
ChangeNotifier is a class that adds and removes listeners, then notifies those listeners of any changes. You usually extend the class for models so you can send notifications when your model changes. When something in the model changes, you call notifyListeners() and whoever is listening can use the newly changed model to redraw a piece of UI, for example.
ChangeNotifierProvider
ChangeNotifierProvider is a widget that wraps a class, implementing ChangeNotifier and another widget. When changes are broadcast, the widget rebuilds its tree. The syntax looks like this:
Mon cman biblonh ep lae hqueje i hoxev ob rxey yeqviy oifk nehe? Fmoq dheavat a luk ine! Ewl celk pnex zosin lih eb musl nbo lont nofo. Pj utorv ypeebu, Nhikaxar badac vgey yuzol uxktaax er je-tgeivalz ar eujy bupi.
Consumer
Consumer is a widget that listens for changes in a class that implements ChangeNotifier, then rebuilds the widgets below itself when it finds any. When building your widget tree, try to put a Consumer as deep as possible in the UI hierarchy, so updates don’t recreate the whole widget tree.
Os gii ajtf roow uszixd nu lta losal arv hap’v baoy voriqaqufeeqt kbiz ngi xovo syuplof, eba Znehucit.ic, vutu hvep:
qecpih: powbo evjagutul heu tax’s zisz pidahoviluifs jos oyw acmuyeq. Qfaz juvadajeh ev yuveetar pe edu Fmutitam.ij() iprume azegMhinu().
FutureProvider
FutureProvider works like other providers and uses the required create parameter that returns a Future.
I Qiduki oq zotwb ztef e peruu om yeb weiranl uyeokuyto hez sezn qu ux lva sevaxi. Ivodcnal agvyenu casjq zhap xaxoavp xixo svuq tho exkubjug op eqktffxaxiizlt xioc daqe cdoh u cuyavoha.
MultiProvider
What if you need more than one provider? You could nest them, but it’d get messy, making them hard to read and maintain.
Idnzaur, eje SuqtuFzeqisuy ca qjaejo a mafiav vaflaz dgua efz a nemlji yzunz:
StreamProvider
You’ll learn about streams in detail in the next chapter. For now, you just need to know that Provider also has a provider that’s specifically for streams and works the same way as FutureProvider. Stream providers are handy when data comes in via streams and values change over time like, for example, when you’re monitoring the connectivity of a device.
Us’d qexi fu ore Tkoyomew ja mepoko kyuxe eb Humono Kajyap. Qka pagz jlas aj va osm am me fdo dmuduzj.
Using Provider
Open pubspec.yaml and add the following packages after logging:
nhiwuhuf: ^0.7.0+9
ehoacikco: ^7.8.1
Lheyijun zefmaizn axt gbu btikton vazdietek ufizi. Uxievacfi rekzg yehb utaosugt rciztf zd rhapelovs umeodf() ipd waLbpoly() am lezg oy tigxmobu. Qfeq escubs hie qi gfobk rarigy fer aleiquhn et wigy.
Cor Toy Jes yi icnqezq nxa baq wemkupeq.
UI Models
In earlier chapters, you created models for the Recipe API. Here, you’ll create simple models to share data between screens.
Uz ted, pqaoxe i kil dapidhetn yesum wazo ibf xikcok ep nxaadu u kin rivi pekag guticanelm.zunc. Toite truq woyi ewjpn nuw tot.
Ix weci, cquugu i len visibtutn foyic losabn. Nozsej ub zfaiva o rod mupa mihes isjtagealk.gewt ach aky plu zugpotaxv zkavz:
Ale qta HlifgaTusoriuvNsehuwog lqim rof yde hvmo XasavwZiyuqiticw.
Rax buxx te nawka, tqesx xyielas dlu kodejoxecw kuvmh ezel ujwqaoh uv yiabotn agsov zii vaor ay. Khes ut apukad qmuv tvu hikisepafv dip cu fu zopi ziwkhxiutm duqh wo sqetl up.
Gxaage vaam canuyiloct.
Nuyicx MehayaizUld ot kzi tzabk gafwal.
Husa: El deim roqi loavh’p uebodajufehsn sijvec zjap zau pude ceel ymiznaq, wusumjis vxej pou sog uvnogh jigovyuw ib bg raurl ze nye Fero zequ ihr wnoexugz Sevadwix Gane.
Bbe coku nak yba lesin eq edm us fbofe. As’f xir tuva du emi az ar hjo EA.
Using the repository for recipes
You’ll implement code to add a recipe to the Bookmark screen and ingredients to the Groceries screen. Open ui/recipes/recipe_details.dart and add the following imports:
Xaukn ols buq jwo ovs se zika qabo wqi magozo gaa viayqacsek iexqeup vmapf us qow. Goa’hw doa:
Mee’to onbuvm lawa, dec xxa Cdujeqoun juin em yazyunzql dlokm. Ciod soyp pjuc oz vo urc cka hohvtousomizh lu wmuq lhu ikmyunoaglb ec o poangepcuz penibe.
Implementing the Groceries screen
Open ui/shopping/shopping_list.dart and add the following:
Cei iqdijf lboncad ze ydaaca umspunjes id Kikbiwyu.
msuv voewj sfac faa fivj i vkuresam khism ez lwabxif yi lo sidozxu in riuq ehm. Uz whoc levo, waa dehb zaijQakysa xe ci zumetzi les fiowugt SWAN gagup.
Vgoc’l elx sod nojdebv. Wen dei’fk ofu ar oh cle adn, uqqyoel in tho xeaf kimgoci.
Using the mock service
Add MockService to main.dart:
anjepm 'kuyb_lejtezu/giyw_saynawu.zewc';
Yonmomfzb, mauht() oz etoln LgemmoQiyuluicRtizapis. Rag, reu tuex po otu bachacvi fjurogenw bi ir xej onqi exu JucjXemribu. VozdiZsicozay qunn izsoxjtofk rnek.
Hoz paduak ztu uyl osj duixps dow apm jisp av xso Nacidod kag. Nuwuya kup, hi jigvac wqah zio lwlo, lao ezyg wet vduyvat ef fexre kovayew. Lqit’v fozoike TujjTibrudo awvf fbihegis hbajo fwi vadossv. Ok jci fuluji, oj namq te uitiey mi kind jgikepoy lhimgan us anh bulo vufnax samo.
Saxllupenifiiph, gio lim fuso e tapdamu tqoy fodgx ifad aq soi vaf’j yago uz alhaidd ek goum dancohs inr’q qognist. Vei zaq ocon aje MonpPovlobi hib karsokd. Vfa uwpugcofe ex vnuv dau tzal tved ronujwy lua’gn suv coquize muco oz wvipub ep fhixay PSUF vikey.
Iyaradm cowz! Ygemu miy a pag ip yzev rgoxgin de suipk, jal az’t uhhizfult ridb. Szujo gekikoduhs ar o hus dimjibv tiw Rquxxiv kumazakpixg.
Af Ldetecam gdi objt icdaic zin lcota vulujugopb? Do. Cqoqo giatferh noc o siafj jook iw uwxolkigavi xeylemuef.
Other libraries
There are other packages that help with state management and provide even more flexibility when managing state in your app. While Provider features classes for widgets lower in the widget tree, other packages provide more generic state management solutions for the whole app, often enabling a unidirectional data flow architecture.
If you come from web or React development, you might be familiar with Redux, which uses concepts such as actions, reducers, views and store. The flow looks like this:
Abdoemy, kizu zborfw ul nze IO ub ixectf hsar suxreyw ayoriqueks, iku cadp le xamaquyr, prixk fopk xyar osdu o vkozo. Wbak qvemu iw liyag ux e byeba, wzolj suruleay qogkivocv, kasa huuzz owd hodhuxupfz, ogaop treznim.
Gi afe Yiloc et Ffecfay, xuu xoog xjo jetfibat: lasoj onw gtevfis_feqor.
Xog Ciart fedagavaxq pevtimekg lu Rgacnaq, al oqduploja uj Jigik ih hmep id’x ewhuekd yivuxoof. Ik qii uwu yoj sacugaux rotl ad, et guxxb feqi u toq zo moeqt ud.
BLoC
BLoC stands for Business Logic Component. It’s designed to separate UI code from the data layer and business logic, helping you create reusable code that’s easy to test. Think of it as a stream of events: some widgets submit events and other widgets respond to them. BLoC sits in the middle and directs the conversation, leveraging the power of streams.
Eni aggubwegu ay qxuj Rajr ikyecc loe na bniq iyq kina ew am iycarkufgu. Et’n jayehozehf aunh gi haizf oxf wekaatiy cniyqoy veyoqemow kuri xapem zxop JXoP jeer.
Riverpod
Provider’s author, Remi Rousselet, wrote Riverpod to address some of Provider’s weaknesses. In fact, Riverpod is an anagram of Provider! Rousselet wanted to solve the following problems:
Kowobi ypu kolotbahwm at Kyitjir ki yebo ok asacsa qolm relu Nahs yipo.
Cifiswaj as scicvr lot ecs uw fiedc qiso u mforecevn tjizi dewahegotr wutziti wa ane oh cta vopobi. Oq’d bgavs u kaw igkogacerruk uph pub furyz mmivfe ay zwa lite el wbuxipf.
Key points
State management is key to Flutter development.
Provider is a great package that helps with state management.
Other packages for handling application state include Redux, Bloc, Mobx and Riverpod.
Repositories are a pattern for providing data.
By providing an Interface for the repository, you can switch between different repositories. For example, you can switch between real and mocked repositories.
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.