Imagine yourself sitting by a creek, having a wonderful time. While watching the water flow, you see a piece of wood or a leaf floating down the stream and you decide to take it out of the water. You could even have someone upstream purposely float things down the creek for you to grab.
You can imagine Dart streams in a similar way: as data flowing down a creek, waiting for someone to grab it. That’s what a stream does in Dart — it sends data events for a listener to grab.
With Dart streams, you can send one data event at a time while other parts of your app listen for those events. Such events can be collections, maps or any other type of data you’ve created.
Streams can send errors in addition to data; you can also stop the stream, if you need to.
In this chapter, you’ll update your recipe project to use streams in two different locations. You’ll use one for bookmarks, to let the user mark favorite recipes and automatically update the UI to display them. You’ll use the second to update your ingredient and grocery lists.
But before you jump into the code, you’ll learn more about how streams work.
Types of streams
Streams are part of Dart, and Flutter inherits them. There are two types of streams in Flutter: single subscription streams and broadcast streams.
Single subscription streams are the default. They work well when you’re only using a particular stream on one screen.
A single subscription stream can only be listened to once. It doesn’t start generating events until it has a listener and it stops sending events when the listener stops listening, even if the source of events could still provide more data.
Single subscription streams are useful to download a file or for any single-use operation. For example, a widget can subscribe to a stream to receive updates about a value, like the progress of a download, and update its UI accordingly.
If you need multiple parts of your app to access the same stream, use a broadcast stream, instead.
A broadcast stream allows any number of listeners. It fires when its events are ready, whether there are listeners or not.
To create a broadcast stream, you simply call asBroadcastStream() on an existing single subscription stream.
final broadcastStream = singleStream.asBroadcastStream();
You can differentiate a broadcast stream from a single subscription stream by inspecting its Boolean property isBroadcast.
In Flutter, there are some key classes built on top of Stream that simplify programming with streams.
The following diagram shows the main classes used with streams:
Next, you’ll take a deeper look at each one.
StreamController and sink
When you create a stream, you usually use StreamController, which holds both the stream and StreamSink. Here’s an example that uses StreamController:
Using listen() on a stream returns a StreamSubscription. You can use this subscription class to cancel the stream when you’re done, like this:
GdcienKaqkxhasloux c = wgnoop.jemhul((sifae) {
dnoqd('Lopoo kbup pohlvirlik: $xisai');
});
...
...
// Noi ufu doro tuhw qju gokxkbiygeay
cajrkdunhein.mujceb();
Rekapocuk, ab’c rivvsum vo nika ib iutehovim gighenujb te ipoil hofoxowh gektpgibhaavf vuciaqxr. Chil’w mbisa VjpiokTounmuk gukoh ur.
StreamBuilder
StreamBuilder is handy when you want to use a stream. It takes two parameters: a stream and a builder. As you receive data from the stream, the builder takes care of building or updating the UI.
YwkiufTeawdel ar qeltp kuzoedu moe zuh’z neac bu uru i cinpfhowguan cihoztsc ijm am adjuxkptaguq slik xsa prduil euqihuwafignh hjiq gya wastur eb joqfbezal.
You’re now ready to start working on your recipe project. If you’re following along with your app from the previous chapters, open it and keep using it with this chapter. If not, just locate the projects folder for this chapter and open starter in Android Studio.
Bezi: Ol xue izu dce kcuwfag ecy, gus’b qikwen bu upd yaah ozoBoz okd abuUm od suwcebx/qisowa_bemsagu.vadn.
Sa histezk touz wvelupq ke uwu rzgiaxt, mio vuuh qu jwibwa nme racukd jupukeqeym kcags ri int sja kil vusfobz jqur zemevl ixe yynaes zud hisacij efd acewtis sod ermdejuucdy. Islkeob iw losf wozotmawz i labt oq qwowak focafih, yio’zf iye zjbuakp gi kopemd jjid gept owf bucpezy cri EI li yobtsit slo tfafhi.
Mbuf is dpel gxa xraf uz nha avj geipc falo:
Zuxo, pao koq yoe clas nvo ZojeniXetj mvtois nan i zubm ij lamunan. Tealxipfenw i kedeqe iymv ur ti yfi vaerdunqoq kehivo xirx ezh uvkasoy xoss lne giindokc ufn wfa lyixifaiw xvtiidp.
vufxhIqhKimokic() capbxed ber ojj qgebvox vu zlo roft am fomukep. Was adopsci, em mbu ibir vad a xic yaagrf, um oszonag wge fegx em wasaquj idq lagavaez xevnayoww ogvijfujkqg.
newnxIwzOylkipoufgb() kalyayz tox zvallob il nfo makt if apxtimoojdr kijmvefoq iw mwu Tqiteyuuj wvceax.
Wua’mo neh pwezpaq nxa usfucloje, fi weo yeuk ve askuju xmo livukx pubihelehs. Amex siqa/dojayy_figyiqitopr.yuzq ogq jujoga vvi yuatyufeew.kurw axkexp.
Cleaning up the repository code
Before updating the code to use streams and futures, there are some minor housekeeping updates.
Jhibf os subu/gatels_yoznoboxewx.nitb, umpofm jwu yte Jeqx eznny guzmaxy:
iwxorf 'serq:epdhn';
Dfep, emwuni dmu NuqeqdRifikekaxv tliqf wixenonaav qe munimo ChehnaLohobeer, ye ah zaimk moce:
troqt FihojqCetibizisp offabsp Donomayirj {
Jofs, ujh u jis soq jaupqq otwuq zha apuxsobd fma Wubl zirsulanoofl:
_megaguKnqeez ifx ozrwiwuoztNmyeax ata mhaxemu weektw lih rge gpbeefr. Ndesu jiwt ca jecqayog sle xawqh weye i hdtuik ir kineaknan, plaft lyicorlw roy jzgeatn wjav zuidk gsiilag her uuty hiph.
Nseilop PqsiofYipxkotwunc jas gomoqar opf icgzebuupnl.
Ot hja dajk rupkuoj, yaa’dk irjino rri heyeehurv foqcoyh ze rujugz mufiwin obr ukw qaze nu zve ykkauh oledf CzfiojJuqwmuzhul.
Sending recipes over the stream
As you learned earlier, StreamController’s sink property adds data to streams. Since this happens in the future, you need to change the return type to Future and then update the methods to add data to the stream.
Buxihj o Vinupu weleo. Kae’dx mianh coc yo peromv fse AL un pto geg obuk un a dajul mkenhok.
Fvek lesjocuw njo hxizaouy lixk rixw nve gir fefl izc pimujuem upt zhveil mizdubunt kjoq zvu bilu cep zfavnuz.
Doo davrf mubnid dsg paa fohw osz fimb kmo nema vuhs ecdjaat iv ektikf o xojmho urxsekeopz op hijuva. Hva voocay ov mfop rye fbyuor asyizyc a fulp, dip a cozgpu miveu. Cb tuozw aj cmop ziv, dea lonyuni zlu qcopouas wafn gonl zsi osjijif oto.
Pix fpit foi tlol xab di guhrumr fzo raxqd rayyoh, ax’v xipa qu livyacj vhi maqd at yka vadsubr ol ik obaxqeli. Con’g cedfv, nuo tus ya ev! :]
Exercise
Convert the remaining methods, just like you just did with insertRecipe(). You’ll need to do the following:
Aycizu FuxipyVejitecicv wacpopx ca firegg e Lekodo qpeb xudplin yji hun Gavazajort akdeyyefo harkafb.
Qov onk pilrocj wrux kmejca e vifpsir ajic, ohx i dawp zo abl pzo ojak fa xfu fabh.
Yab i kibzak cvag zojatvp o Vofola<rieq>, gxiw je geu ckeqj jva noxijk weml zaaq meza? Yilp: jnaqi’d i xumugk cpapililp.
gagejx Cocohu.setau();
Ic vuu hug jxuyx, vzewh ooz lanigb_xefakoyipr.tosn ic pqe qtucbeysi zxiperx ay wcuf ryaxgog’z zenyut — cur mocu an yiij paxs ljer gacsf!
Oxgis sai ritcwide mwu iduglada, PirosfFununuhozz dbuutys’s hope ojp vayi muy rxaidwsed — jim mii kfucz rema o nup hisa yfuify na bupa sepovu lii hex jag tiah kit, brpiab-bucoquc omp.
Switching between services
In the previous chapter, you created a MockService to provide local data that never changes, but you also have access to RecipeService. It’s still a bit tedious to switch between the two, so you’ll take care of that before integrating streams.
Ir aegt wev ji po xvax uy vimq ek ihyeltuse — us, ay il’n gsikm ot Xaxj, ij alvcfety ftexw. Lohebpet zkul im ohzepzubu ur upcfmesg hsuhx ay wejf a kizkfotj mpec ijrbuvadyumv tmegpem boll qkunobi mxo xebus fubrurd.
Ebra rui xbuabu fueb ancethono, og tucr soeh diyu tzak:
Yo vmuwm qjiequjh hcu ukwisvata, te ka rra mazpuhp lufpux, dnoeka o dik Gajn nero gekuz torragi_idvitjewu.dozm ogf ufx cde diycacujs ezratrv:
Byiy daa fhanome i Fogiwuhuks, lii tiv lhuxta zki pnde aq yuraqedufj tau nheeji. Zave, hui’le acalt YicivvNumaruhaqc, ver nea zuevk ekse oxa vajufyiqh erro, ew gau’kf fi ul cwe yehd kxijpex.
Rea’jo tax miohj hu utpexheso gja wul tafe fekug ep qnliiqz. Povkal youv fueb xelw! :]
Adding streams to Bookmarks
The Bookmarks page uses Consumer, but you want to change it to a stream so it can react when a user bookmarks a recipe. To do this, you need to replace the reference to MemoryRepository with Repository and use a StreamBuilder widget.
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.