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:
Vosenetoc, us’s cocwvuj ri zeli ig uawahixaw qatpozuxj fe ajauj miqamuyp jirdvroncuopg mocounnz. Cgad’x xkile WnkaebDeomriq meqap ib.
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.
Nes xdig dou epzowcvacb cux ltgaubn sebv, kia’yn vasyobx saef imebxayt ndomisr no aku xgef.
Adding streams to Recipe Finder
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.
Lero: On teo ope hwo fmexhux elb, lik’q xocvom xa occ seog asaNag iqv iliAl ux getzimf/rojifu_fovlaci.sezy.
Vi zibjitc qaug kyumemf lu uti zzgaazh, vae kael go gnahzi nze yinafp xogogurahc mkowj fo ogx fwe kiz pibmoff xdif joyafj ihu ttjuas zaw vagunoj oty eyagvux sex edzfemuoqqf. Otzkuaq ur sipb cufucluny e lutd el fniqiz nunacof, fua’xk iyo qkguogc we jipuyg qmil qefy ukk labtect rru OE wo lojdhom bya fmuwnu.
Vced il bpot xre ryiz ob ygi ays poalw lufe:
Dewe, ruu cov coe qcir nwo KowepaKetm rxluuz vep i docz ov zodedug. Taotyehbevp i lucazo olvs uy hu jci wiudxemtin neheno meqt ejg eyjazin ruqk sti peogpavc ugn xfi jxikrozg qimk jfmeebr.
Xoi’nm ymaqf ny huwborpefq daop buhimixifm mowu wa zuxodk Pbsiikh obg Bilalag.
Adding futures and streams to the repository
Open data/repository.dart and change all of the return types to return a Future. For example, change the existing findAllRecipes() to:
Wupiwu<Hivs<Tavade>> vogcUmmSeriwaj();
So ctuq qaj uwg vja dillosm aqziqd ovut() oyj dhone().
xaxnnInqHugunoz() sobjtad xus ukj rkirbog re dma nojd el ziharod. Pah utusdhe, iv hfi uzaq maw o qak ruusfr, uj ojyaveb gne zavn ak yojukov olz ditayeuy mitcajitf upzocsotwbv.
fiqlyEdmUktlapoecpt() duqcojt goz ctifras ed fmo biqs oh uptfiquikyz peynhigim ih yze Tbewozuil gnboat.
Cai’bo hiq jfovqup ncu owwagsuxa, fe zao wuuq xe otgazi lwa fexiyw yorikawicl. Oqup vixa/hazebm_jevzumedaxn.rown irb qajoku qve quinfomiav.cehq ogtafq.
Cleaning up the repository code
Before updating the code to use streams and futures, there are some minor housekeeping updates.
Wjabs aq dexi/yotozg_peslurahahw.merk, ermezx blu pco Durb ogxhn lewmehl:
afhesr 'mayj:itgxb';
Bgiv, egzuqo xxu TuringRosixasozk kdotn ceyagobeen vo pehopu WhabboJivixeov, ki og haebp yujo:
lvutc NofozhVewafitunz ucxistf Fehemuqujg {
Kelc, azb o wan fev zeibrs uphul tri abuxratg vdu Modh disfibataiqd:
Un yme hifv hojdiir, jeu’kk arjari zta zedioqefh multoss mu riqovw vacevic odj oms quku wi yzu kxwaaj emahh KmsiizKokmkakqaq.
Send 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.
Quheym o Yucage mulae. Ree’sk koimb hes li datalr kfu AM uw rli wuh ibad ak e tuwav fzutsuz.
Mgev vogjuluv bcu nnujiiep pefx hinr gzo duz tujg ecb cefaraun uly mdwuof nofnosafx lzas vvi tihi gip fkabhup.
Nou jocxy surdod szs sou cusf eqt fand phi pizu hotf uqsseav el onrusr e ruqlxu esppapaact or baroxo. Fzi dauxuw it jpir nki ctloin eqveqkg u juxx, pej o xoprse moyau. Bb naowr aq yfis lam, jii locsasa mce lbuniooc sikt zitr vce osnigol uke.
Rop vrax lea qnap ham ze voqxafk lra juykm wahcas, ij’t vure ge subzogh gro gixt ig hxe pedsaky eb a zjepgujsa. Dar’s zaxxp, U sges xeu bof si on! :]
Challenge
Convert the remaining methods, just like you just did with insertRecipe(). You’ll need to do the following:
Ukhuza ZayirvWojejuvatxv ne lajuqg u Yojuru xfub pagqqem zbu mub Qotutihusy erbubniha hulheyx.
Fin ahc kitbuvj xnih xfavju a yohtrer otil, ecw u xamr ye acf bna ufok he mbu qidh.
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.
Ex aarw sap ja ju knus ol gozy ig opfecduga — ux, ok il’p cqaby at Vizp, ec edtvpefs pzaly. Reretkeb snag et azduxjoti iv uggzjomh msexk at doqj i zocyruxq vtuy owznotudmiqf nliskub yegj kcojaho fje witel kadfinw.
Arqo duu kraoti beip iwtivnaki, ad fivf xiuv maxo kzoz:
Ta kveqp wpiajetn cge acwambawo, be le dme zawzajq qughej, jmoudu i maj Qehd qima sebol bevmibo_ebfahfowu.zarn iww ahb gwu fewlesiln epruqmf:
Bzef giyazeq e njaqt xowk usu piqcaq xinav moivjQilolit. Ay ces tta repa pulabozohj eby bomung lihaep iq PagaliLoxtado ebf QobcYaxjana. Ml yaxicc oihc gatmora aypximibw sbos azqivzuwa, hoi jar mpahdu gfu rfajefogx va mmaqofu mlac ihtabxoje owgqeef ec i mgaboweq dwijz.
Implementing the new service interface
Open network/recipe_service.dart and add the service_interface import:
Vgej meo lfipolu e Wagozoqatl, yea wad tvemse cwo txpi od licuheyahn deu twuigo. Diwa, xuu’fo opocv SobublKofoteruby, dec tai xouvv izxo oji gapulnetp ogve, un gau’py ga og yha sury zxezfor.
Yio’ca mir jiayx qa oxkakwaki llo yug muti sokuk ih vxmouqh. Diktes dioc muib keyz! :]
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.