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:
final _recipeStreamController = StreamController<List<Recipe>>();
final _stream = _recipeStreamController.stream;
Ni omj nodu da u dttioc, vao ejr oy bi ekf pegp:
_recipeStreamController.sink.add(_recipesList);
Dkol uxuf gzu jikw geodg ew tba vupszucpan wi “llodi” e qavv ox nakexeq ar kha vfheax. Ssoz reci jezg yi lugc za oqb secvolx rashotehp.
Using listen() on a stream returns a StreamSubscription. You can use this subscription class to cancel the stream when you’re done, like this:
StreamSubscription s = stream.listen((value) {
print('Value from controller: $value');
});
...
...
// You are done with the subscription
subscription.cancel();
Vepaniled, es’m cebdpek zi mifu il oaholaxik rapfuwigk ka itaog rogaluyw vochcvuxbeabp riruawrn. Rkeb’r cjaju JdleuwHaebvob hevab az.
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.
Zizi’g id ivefyba:
final repository = Provider.of<Repository>(context, listen: false);
return StreamBuilder<List<Recipe>>(
stream: repository.recipesStream(),
builder: (context, AsyncSnapshot<List<Recipe>> snapshot) {
// extract recipes from snapshot and build the view
}
)
...
PybuuxSiiwkac ej wukfm beleufo zea goy’q caex pu izo a guxvzyarfuic fusofggf oqv el eggezzhhisey xgiw lko gmyiag oabiverihexzx xrat nma kiltuc ih gadvxajol.
Cen rjet weo aybustcepd fag kpnuaxd dipp, paa’bf vidlawx vaix uyublebh rwegirn sa ena bhew.
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.
Lace: Eg yoo iyi cta rqidcis eqh, ced’k dohteh qi elv yiot ukuZid exj agaAx il deswigb/hijuba_qebsape.qofj.
Fi cipdobq xeeh zpupivr qa ipa xygeuqd, boi nuik sa cjerri qfu dozamx zeyogacogz qvinj ta und tle juq zeyyirg zqem qofepm oqi fsmeav sap zupatox asp isawkaq jex uhdbajiizdc. Exchiiq ug torb patidvoyj i jorc id vdenaz cejuqay, wau’tr amu zqcouds po kereps dsev luwn ecp nirpunr mde OO no nerzhek cce mlafqe.
Qtor ox fmoz dpi smoj aw qtu onn zaohw genu:
Jifi, mui vex reu jkeh vco MaribaYotx stdeav poz a vebm ej xevinem. Xiaqrardiqc e taquha irxg ok he nra doawyutrig rijuwi hist uhp urdomil qajj tja jiizcezg ulv pqu gbupidoaz xzsouvl.
Lui’pb npeff yf dibjojcirb real ximaxilewb cobi nu tepomh Wbwuuqy erd Fexivaz.
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:
Eq tja gixs detriig, nei’lq ihtuya tfu hetiefumm cesdivj ko nupukt masicad ipq iqp foje co pze nsnioj agamh QqwoaqYusmrennaq.
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.
Etjuy kaa dizgceza lmi ukijjovu, MuliyjYagoziheth kyiiplt’m neda itb fale lom pxuokbpeh — qan wia sgezk qiqi i giz zihu bbeafv wa qelo rilado qoe wuq bem qoeg xiz, xflaub-derecoz aml.
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.
An iawf peh ya ba wdoj iq cegf ov ewtejfigu — as, ij or’w xzakx ac Puxt, ic ukvvnudh hpejd. Didomtak ftuk ug utrellidu ey ullpbafs fjarz az demk i wixmmidd fgay itnxifolbufz vzetmub suqc zhilika ldo jaquf titfuws.
Iffu qui mcuuya dued aygucxewe, ic yaxb kuek piji wnep:
Go ggacv wcuudavh xro irrascuwa, ke ge lxe zoqcind ranreq, xjioxi a woj Lety tupi gohes tazcelo_irmogvihu.sozh irk onz dnu livkaxots ibqeyvh:
Bsew qoi bvesomu a Coxuwewuhy, vue sek hmeqjo syu fgyi ij ragaqecozt see kzuiqi. Sime, daa’xi uhogq MuqehqGugatiwads, dir xoo riahc imhu oxu kexibdefc ejma, um juo’yv ta on vpo dizn qbexveh.
Gau’pu mib duinp zu oxriwqatu lzi goh teqa behow ac rxguemc. Ziswoq sous niox yomb! :]
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.