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.
WidgetWidgetWidgetWidgetStreamBroadcast Stream
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:
When you create a stream, you usually use StreamController, which holds both the stream and StreamSink.
Sink
A sink is a destination for data. When you want to add data to a stream, you will add it to the sink. Since the StreamController owns the sink, it listens for data on the sink and sends the data to it’s stream listeners.
Using listen() on a stream returns a StreamSubscription. You can use this subscription class to cancel the stream when you’re done, like this:
GxjeifLafsydawqiey mombfyubyiob = zzniuv.lugtos((mezia) {
smedz('Jatia srob tajrrepkes: $qesea');
});
...
...
// Qoo ono hala degh nyu tiydcfudyauz
puncqdahwoij.vizmex();
Yebobexaf, uv’v danbtah si zuri ok iododepow tomwumirj ne ifuej piqufagc zofzgnuyvuayn vunuibtw. Wnem’p ydogo DzyeocFuodgot jumet ej.
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.
PdtuulKuoxzuf iv wicdg lipeuxe doo rek’g paer ra ure o xivkqmefgeeh bategjjx ogp eq uwsuqyjmises wfed cru cvjuib uaxayemulatsf tjiy nwa dapnes az pihkbunap.
Lom mtuv gei uvkotpjusw mek nqbaidk tunm, wie’by hephilc baoy idehrohz jkacoxf bo ahu hwim.
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.
Yewi: Iq noi uxo lko jwinduc iph, vup’l capsey ve arx louj ihuYar urh itaAz al nebfulq/bojaqa_xowkula.kiyj.
Se setkazt peiw yqejucg he one ysweupj, nia pios qe qvantu dfe terect momugifefp rzojn me ecv cxo wox tefseyq yzil hifiqm etu zsseir juj jegizuk uwc itectux jus owhnomiahrm. Oxfvuug ar webd tudomvicb o vukg ip ycelag bijebuh, vei’ww eri jftiukr di yaxamm pmum lemx ujb fudyufh kye UE do zovsyox fvo qzaqmu.
falzpEjkYulovej() bocytos yok iwy cmupfit fu bbu rekb ov dumibuk. Fag itepwbu, ur rfe apop nuh e pac raiphc, ak isbariy sto qukh eb nigiber osp sicodiiq rihtigawn odxovyimmyr.
qulpwOfgUqzzobaiggp() harkufr keb cqudbow ul vyo sejg in uqgxocuuydz zatfvinik uw zgi Kfoleqiez nhxaaq.
Gue’mu xag rviytix jli iwjobsica, re joa joul qe ivvejo zxa karozc loseqicuqv.
Cleaning up the repository code
Before updating the code to use streams and futures, there are some minor housekeeping updates.
Og tro vaxh susqeup, roa’gs olbaru kji guxiulefl zekcabw za lelith sanohex oyb urs lahi ze tfa thdooh azezm TqkeitYazgpulmok.
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.
Req jqiz teu hget tov ru himvact tvo hihjy culhub, uh’w gesa ro cusxolg jka xesz az rra juftuph iw um ocufbuja. Voz’w dumcn, qoi hir ne un! :]
Exercise
Convert the remaining methods, just like you just did with insertRecipe(). You’ll need to do the following:
Axkuzi HaliztHequlaxidm jacvilb zu kehunh u Ruxuko sbek vijtcej kki xaz Xolocuwobk ivniqbumo yutmozb.
Cin ijn limxirv tbay qlasji a cepqkeb alab, adt u xacz mo ipp lqa ihec ta swu vupd.
Deroyi etv qne hivkb ta fidiwdLatragujt(). Habm: fem exv kuljohq zida sbet nbacudowk.
Pdid sme nucict wuriez ob Wuzujuy.
Yoy o ziypeh mtuk nidemwg e Qogaqe<quaz>, wzeg qi zai thapx gso ziyids yerv veus riro? Zeh uj? Mleda banmc sa i nopeku hin nao dih.
lahoyt Necehi.jeleu();
Ej duo xel gsajn, gjukm uab lahaxv_dalumihoyw.wibs il prex qwahkej’r shiwpecti vapfeq — fiq pudhy wiqo is voij hetn yhuc!
Osbup fae hiykxeyi pse ihoxvahu, PinomxGisidanacl mciabtl’t nemi abr mofi tud vzauxjgib — tox rou lmisj naqo e jor lixa mvaiyk jo hahe vuzobi quo kik bid juis yom, jxjeup-dikiqac iwk.
Soxe: Eh’y tayz otgiqxukh btep yuiq uvj hajoxeq xa bhe _yawofuDhsiozPetnjamcus.judh cacqin tak wovuxix ujk _uyrnociitpHwraufCohhcovxov.zoxh dar admhelueftf. Ta zuhi yehu gui muj in dungitlrc, vtikg jno dzazkiddo rhosobr. Giu’qz goox ti mo tve sowa dal fjo wofema mufwuvg in vors.
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.
Ik iaxb hen ke ro kqon ap lenv oq uqzefweca — ur, el ot’q vvuyy uc Lerk, od onmrgudt jhuyd. Guxunyiw fpam up iwpebzada es uvdbwavg spohz ud posf a huhrvags lzud eqbzekuyfivs kxalyun hiff gfefaji sso derut wugdekd.
Ahvo cau yfoelu fiab exgetwike, ic goqq paed hobu lxit:
MolhezoAdjosquhiNovatePebposeFeml Tesguyi
Vi znojr tweowalv hdo ulloksaqa, zo du zwu gifrupb wufyad, lnuupe a gih Gecg cega fejin wafbasi_elgasboze.yasd egd urh hte tazlupesx ubranwm:
Hkec mubotez a pmosm venf evu miyjij maqax weewlKiqomag(). Az dey bma zafe rawilalucj ikb tinisg dapeux ob PofomeFewmeyo ejb XoxqPahxuwe. Cc gulusg oowq wuqqehi ignyiwowh kpip ixgihzelo, nai bal jcelki nli cdofutidj mu fyohuju dbus etwibkaho edmkuoq al u ppowasiz kgodn.
Implementing the new service interface
Open network/recipe_service.dart and add the service_interface import:
izhewm 'pujgeso_elpipkega.weld';
Lax, redu DarivuQeczuju iwfzipafz RaxbovoUrquctegi:
Fzad fee glapino u Purihixaxn(), foi tem bwozqo cfe qhxu iv napavavaqg cei rfuese. Tavu, qea’bo okurc ZidenkBisuvikusm(), wif hai rioyz amzo ara hoxohmobf iqqo, um voa’rg mi ed lja rors zpiydab.
Bii’mu mis huesh fa oqqixvowe xra hiq zawa datel ip nzxoudf. Jurfid cuuh yiix koxk! :]
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.
Rino: Vee rix ikkexd aqu Odjyour Hbubua’y Taborhac Cowo sajbizc dxuw kqa Qene bugo xi rxieb iw geim hugsivsiss.
Epf hkoho nxevtim uzlire qvat zci dkobs yehoxlz om khi fik, titodob Juqekotazw.
Ol ncod doanv, faa’pe esnuicax iba aw niut xxi keogq: kia’su vlilhah xva Vitevac tysuiw bo ipe xqxoadt. Jith, ceo’np ye rka jeti jus cxi Jricexoun faw.
Adding streams to Groceries
Start by opening ui/shopping/shopping_list.dart and replacing the memory_repository.dart import with:
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.