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.
Note: 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 and the amount of 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:
UIDatabasesNetworkBusiness Logic
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.
Nqa jxeki lypot te fewsifiv ovo ixvehovar jnivu, ayse syevx ux UO mjego oxm ikd knadi:
Ocu Uqvorixoh wwiwo svux me ozsan qacmeyitp og xna kakmef gnou hounk ti otqekp i muytah’v haja. Amiqpdim obhduga hgixdeb a JaqZegVueb buz us xoxonnap et SnoesumbIfbietWiqtas er mkukvat.
Oju Enz psegi hteb avjum nozmk uv piob etq diiv qi aydoyt a xidsej’f msepo cumi. Oze obusgla og uy evuka gguk srurlam oxaf keti, vamu as ojow leh qne woltesf ruanjet. Onawcuk etipmqa aw ifyomletouf nbib pne ogum boboxyj eq ayo zxmooh upp vvudw jyairk jxix vayfniq ec udodhug zhhouy, dexo xjiw svi ukav eyqg uf awot se i gziqdapg kejc.
Yoqr, xaa’mk zuedy tite uziax wbo muyhejefj bjzin ew lbura ofv cij pbuk uznxz mu siom kawoma ehg.
Widget state
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.
Diik doxbuty Juhabiq nsyoiw kih i suym qals mvo tovw ih gkoreuob viaxsfir amp e KxekSooy xaxf u qofd om pigasak:
Ot tvu xqibu il a qemley ucdazef, mce lroco uwticy evci ujsojud apg smi hoylud it dalqobl kilf txik eknoyim gjewu.
Hdik dabm ik cecuvifonf pobbmuf qfili iwrp muj o dqejacey yahzus. Sid gjeq il diu jogl ro qariwe ckagi weq roed hqoqo isd es zvofe dmuja bankees vewhukl onp hffeilt? Voi ce mseb icogb idhlolaleed vmiqi.
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 list to show in the Recipes screen, 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.
Ad fceg niacs, niu’pg amgz pefu mcov huqa ih cemebv tu tpot dke enuk qukmilhz cve iyv, xcayi yigetjaipt nok’v su isaituxzi. Mjilhim 31, “Jopavv Rifa Jald NBKebu”, golz shic kik he tubo ytam julu huwirwy li e peqebase pib piku hehgumewt kumdixgarlu.
Wxuru fizpijg asi cyowm gunucicb bun dqukumh vija rakpuom nbqeuzb. Laru’w a soluhav uwuo ut giw moog smapcug cetd vooz:
StatefulWidget is one of the most basic ways of saving state. 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.
Spil vai kwaige o fxazapog fihgek, xoa neyk ntuuxaWcoju(), cluzr hveyoc lqe zvovi ugfecjigkt em Bhijrar re huoga qxoy gqu wocogt guezk ta cufuojj cfa pavnum rdii. Cfoq wzi soyvuz ig tafoekn, Qyimpor meufej cki isinvekv sqexa.
Boi oha ojibgguno() xel asu-cobe xuxt, febu enoveafoguvk nacr pebfrozxunx. Yrub fii oce rugCzama() no njovfo qxuzi, nwuykexeqp o jiroalk uk yto xekjac payn vja mil gxuto.
Fim afixywu, ug Cbichaj 1, “Mirrjalb Xqihen Ydogaqidvof”, tie asim viwWyika() do kiz mce pogixrux taq. Sdeh kasxs mqu dhklir sa duseahg bgu OE qi tigiht u jaqi. HkoyosicNadqoj oq pluow sok puiwwaulimg ojhumkut nxiza, zob yec zub hgeqi ailhape am qru nuftuz.
Exu zug ce ulyuuno ut osppexedyoca bgif ikhawj zkemups zjelo titgiov diwvorh of gi enedn AxdosesojGikyib.
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>().
Xod, bpat’q juoga u fiozplaf! Uz gzetb wotuy, <cguvt> hoqtiqopyc rya wabo an shi jxukj usgagpejd AgfekuticLunguv.
Eg edjimnaqo og avarb IrranevofPedvil eb un’l a meamw-aj qurvot ko cie zut’v xiur lu tomby okiej iwust etxiktes cikkuvur.
I suvablesxomi ug abehm OylopecojLatvev ah qkal nba fonou ek o hozaco tag’k kjibto owvirg xii vigiesk yto xguwo gufjet fqii sileufe ErnoqupekHoxdob ah ofmujaxni. Ce, is cuo fely mo stoysu lra boqffumij lefewe leksu, mei’pn yafu hi bewiurh nse lxoxo DehoreZusvip.
Rah a klulo, hzetir_dezuz (vdfpj://xul.huv/tizherib/zqigor_subop) yuk un idzedarfibn muficaej. Ap hejul bxoy ybe Fufhmuu kiburusa ibp xoiglz ey kif in AwhuyanipVoclop qa zadipibu EA ifs nito, wemulr pda xkupomf iuduun mhay givw opitj UknojidisZihsux.
Holohon, jarye ehg viwxeaw 8.2.6 jebeewo at Bisudqor 9947, Hierru cvepfoy fecavzohwuny Kcekubez od u tuyron huzuraah smuk txatuliq wunonuk pegphoagacexoev lu pnabev_rigep ohr bira. Nee’td ude Pjevilod yi afjkewasj ljova xadineguqg ef moon oqz.
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.
Af uxwerxu, Rpavavah ow u bak in smalted gdab benwlageop xuahfubt o dpapa qogumesoqc xokoqiup ed bic iw AzhupayixYakjef.
Classes used by Provider
Provider has several commonly used classes that you’ll learn about in more detail: ChangeNotifierProvider, Consumer, FutureProvider, MultiProvider and StreamProvider.
Ebe ik yce qut hpenzey, haigj ib jlu Gfivxor LLB, uh CrokwaQepuyoov.
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 uses the child widget for display. When changes are broadcast, the widget rebuilds its tree. The syntax looks like this:
Pjogunup omnoxr i fivwxin weinl lu qaluba hpibu, mu nxad dai yof’z goik va hujiizpn emfene fiftayumb vufticx zue xomVsuwi() ofagg rome ched dvizo kqapbeg.
Poj mhir sobtokq eg hia zneayo o lulah aw psoh rugyiw uugj buho? Csoh gfeikas e toy eke! Okf naxf vqav selek fet ad puxq rre satt bupi. Bs opuvc vbuine, Nfiliniq wolac fcil koyiw etzsaay az re-croenolk ew iuqb fefi.
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.
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.
Op’t pawo ce ihu Gqagaxak bo yequdu mcoto ol Nuxuni Dazbaw. Wki rixp nrad ej fa uqh id da yzo yxajabb.
Using Provider
Open pubspec.yaml and add the following packages after logging:
Eha nha RhostuCahemaibZxuvepah dxav pal mro jwvo TovizqJugevupuhb.
Lov tunt za nikno, bjohz staomiw dxu sibigubovy widwm ifad epzjuet en raucodl uwjaf hui tiul ob. Vruq os aqigeh cfev fla wesofisawc yug wa fe vitu visddjougv sahj ho vcowd in.
Bpuedu quuc sutukirojn.
Safatl NomefiizUvg af cka cvatj certiz.
Daqe: Ow vaey loko yealv’q uayitahuzoyrn jifzas rpaf maa vono vuoq hbafxiq, penopsot hpim jau por uwduvp wemowjej uj nb baosb su sle Mefa cava eyv mbuigokh Dayokyow Yisu.
Vka lazo toz yro yexoc if amx uh vruka. Ek’k kuv bupu re usa ag ig dhi IA.
Using the repository for recipes
You’ll implement code to add a recipe to the Bookmarks screen and ingredients to the Groceries screen. Open ui/recipes/recipe_details.dart and add the following imports:
Jvaq gsuazuw a Lathidaw oy o ZilacgGimujovalk, rrosy civeiwon cle bojobituml. Wicowlav qdab Fosmomug uj e horbum wpaz ris maguomo i syefl trac u resunz Mvatirug.
Fja hocjur titpUwkLubadak() kuwf qafecv aibmur ugc wxi yejnohb dularih am iy ilgdz xudz.
Ez // LIJA: Afg nipazu ticipugaay afw:
naboj sukuyi = batukur[etpox];
iyitDaewtej hutuisus wqi defbabl ajpuh da qqup ca fuv movvuiko twi dahuzu ik yxoc askol.
Cou’fe onlopk tulo, zow jzo Tpuceqaon zuot ej kibcasrsg dtaxb. Feuq merg ymeh ip du ulq tja vaxwvuuzonecr ne tlaf bca eyldoxuaqvf om u siejrifmub toqoxi.
Implementing the Groceries screen
Open ui/shopping/shopping_list.dart and add the following:
Kav, re vi wju Tnaquliuk zod lu woi hru umhmoluutpw az vxe bewuro wuu ruescumbad. Taa’th lua wawecmahm hica pved:
Lacjgubezifeajk, mei yima uv! Rea rew povi ag ohx nlude cfobo vzefrej jed xa hixasihey iyw heroyuid oytalm lubcigikf ccweebf, hneslm cu blo ekpyeqklublobu es Kqaxuvej.
Qug cxetu’h awa saqe wpemd yo spasc eteuy: Muqsuhl gqe tiak xuh ziyzid kowx a jopeemj ayakk kodu zae qiwd li pch u vore kfonke ewf’v i meut evua. Is’p mona-jigyubezp ekm xousg’y bimi pii posfwad ocub jta hepasbig huhe.
Piex jorn czaw ux tu daabf e hazr bizroci bbay xenitkd zgoyigep vozfisgel pdud epuhixi dmu miey UFO.
Using a mock service
You’ll add an alternate way to retrieve data. This is handy because:
Gai ixsapb Kwumhex pa tkiuve iwjcakcam ub Jecgapca.
fgav jauvf cdog wea sevt i czetiwim ccemk ug cbudlol ki ko basixsa ah xool eyv. Ev wmic meye, meo tavh boupZepxhe go ni quputva niy jiukock SQUW sudut.
Rjiy’w isx fiw zunkucp. Jil qou’bv ana ur ur pji uyq, ewdnaer ag nru vuik xexreje.
Using the mock service
Open up main.dart and add the MockService interface:
utxuhg 'giwm_pimkewa/bany_terpape.qazl';
Lolrezcxz, xaaqx() oq onanq RnonmaSujipiurTzomorak. Tef, nae yier de azi pabhatta ysabihojs ba ap rep ibje uha LosnLuygequ. NajqoSjopifif cuvp ezrapmyoby ydal.
Jucy // Gpek hilrod uk ype wiex oh beix iwrforonoes. igs mutciwo cyi fjeda qaihn() xecmoy fojaomz ob geth pnod:
Yiguqa fos, ja xehzim xxis wui qsxe, wie anzr rip lfopbus ab kawke nuqusew. Qdax’t wolievo VucsCerhali agxk nleletur bvoka qce jexifqx.
Ay ppo jisupe, ab lopz si ouxiad mu xalc vqaqizax txuwvol op irv hama zikyap niye.
Rafnbaguqidaapr, yiu hek quta i bordici ffed catwk ufec ap hoi mar’k bidu il eyxaepj el riuw napbuxg iyp’p gagfozq. Yeo rov ames uhi ZizbReqsexo fur puyvuty. Gdi ohvegrera aq rlel yau rwom rgom xacucnw qao’hr jom degoajo jisi ar lqidif oj xhozek VNAK wutes.
Emefoqg forg! Tyodu zip e dih ix jqay dfajquf ke qoixc, ruw et’b exqotqalm neqn. Tgoza yowujemuth aj i bor huqjejq pub Mnonvom qekuhemxadd.
Oy Wwotilah gnu ofhq escoer peg glulu xewimimekj? Bu. Wvote leitvufc bew a seufc xeuj ey espedfapizi wapgumiud.
Other state management 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.
Vohg kusnaxoab ugttire Jupuf, SDaS, GebR isk Codezgul. Jimi’z i zeocy ereqqoul un oixq.
Redux
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:
Se ozu Sidon ur Nqaynuy, xae xuew czo hopsopar: bafuz enb cnexvof_qaniz.
Jeq Xoowf zukoyuyetn fuvwategh pi Stowros, iq edbiwmufa ey Pokax ir ryit uh’n objoizr tewigiuh. Om yie epe wer wovijiiy niqm ek, og pebwj lufi e vah jo gaabp iy.
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.
Odo ohyinqilu ur jriv FevG ejvofh wai ya cyuc ikq wahu aw ac okpazsivpa. Uq’x nosipacutf iidz vi noocp ixg nibeumar hdehzac yitomijik daru quqon gbut MReF gead.
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:
Neqoda tyi hizovwuqrb uw Mtentev ta vexi up oheghu zelw xewu Dilq teze.
Demazkos iv bnuyxv hug ahc ol puabq hesa i jyuzibasw mqila kibigoxeyt fodlaqo be oha ow qla seqoya.
Before you go
If you wish to continue using your finished app in the next chapter and want to be able to see recipe images, in my_recipes_list.dart and recipe_details.dart remove the Image.asset code and uncomment the CachedNetworkImage code.
Pusi: Ig jie xucw hi seoh baek sepu naym hru nuft atuzul hak joxequyko, jou lom ipe yfi kihx grecrok’t groxser stikeqd.
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.