<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Kathy Walrath on Medium]]></title>
        <description><![CDATA[Stories by Kathy Walrath on Medium]]></description>
        <link>https://medium.com/@kathyw_39223?source=rss-fe67f3a27347------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*OWxJ0V46ratF_z-r.</url>
            <title>Stories by Kathy Walrath on Medium</title>
            <link>https://medium.com/@kathyw_39223?source=rss-fe67f3a27347------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 07:42:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kathyw_39223/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Dart asynchronous programming: Streams]]></title>
            <link>https://medium.com/dartlang/dart-asynchronous-programming-streams-2569a993324d?source=rss-fe67f3a27347------2</link>
            <guid isPermaLink="false">https://medium.com/p/2569a993324d</guid>
            <category><![CDATA[dartlang]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[asynchronous-programming]]></category>
            <category><![CDATA[programming-languages]]></category>
            <dc:creator><![CDATA[Kathy Walrath]]></dc:creator>
            <pubDate>Tue, 11 Feb 2020 18:01:02 GMT</pubDate>
            <atom:updated>2022-04-14T11:38:48.880Z</atom:updated>
            <content:encoded><![CDATA[<p><strong><em>Note</em></strong><em>: You might want to check out a </em><a href="https://medium.com/dartlang/dart-asynchronous-programming-streams-dab952023ed7"><em>version of this article where the code is updated to be null safe</em></a><em>. (The video has not changed.)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/272/1*7v26fZu7zzY0QSBQAwj42Q.gif" /><figcaption>A simple Flutter app that displays data from a stream</figcaption></figure><p>This article covers one of the fundamentals of reactive programming: streams, which are objects of type <a href="https://api.dart.dev/stable/dart-async/Stream-class.html">Stream</a>.</p><p>If you’ve read the <a href="https://medium.com/dartlang/dart-asynchronous-programming-futures-96937f831137">previous article on futures</a>, you might remember that <strong>each future represents a single value</strong> (either an error or data) that it delivers <strong>asynchronously</strong>. Streams work similarly, but instead of a single thing, <strong>a stream can deliver zero or more values and errors </strong>over <strong>time.</strong></p><blockquote>This article is the third one based on the <em>Flutter in Focus</em> video series <em>Asynchronous Programming in Dart</em>. The first article, <a href="https://medium.com/dartlang/dart-asynchronous-programming-isolates-and-event-loops-bffc3e296a6a">Isolates and event loops</a>, covered the foundations of Dart’s support for background work. The second one, <a href="https://medium.com/dartlang/dart-asynchronous-programming-futures-96937f831137">Futures</a>, discussed the Future class.</blockquote><blockquote>If you prefer to learn by watching or listening, everything in this article is covered in the following video.</blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FnQBpOIHE4eE%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DnQBpOIHE4eE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FnQBpOIHE4eE%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/19f7572c0ed7e65b2b45fc00703972c6/href">https://medium.com/media/19f7572c0ed7e65b2b45fc00703972c6/href</a></iframe><p>If you think about the way a single value relates to an <a href="https://dart.dev/codelabs/iterables">iterator</a> of the same type, that’s how a future relates to a stream.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/429/1*q9cqGB5uXOX3tNw07SoJnQ.png" /></figure><p>Just like with futures, the key is deciding in advance, “Here’s what to do when a piece of data is ready, and when there’s an error, and when the stream completes.”</p><p><em>Also</em> just like with futures, the Dart event loop is still running the show.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/0*UVy8BLEUm4CifwDE.png" /><figcaption>Streams work with the Dart event loop.</figcaption></figure><p>If you’re using the File class’s <a href="https://api.dart.dev/stable/dart-io/File/openRead.html">openRead()</a> method to read data from a file, for example, that method returns a stream.</p><p>Chunks of data are read from disk and arrive at the event loop. A Dart library looks at them and says, “Ah, I’ve got somebody waiting for this,” adds the data to the stream, and it pops out in your app’s code.</p><p>When another piece of data arrives, in it goes, and out it comes. Timer-based streams, streaming data from a network socket — they work with the event loop, too, using clock and network events.</p><h3>Listening to streams</h3><p>Let’s talk about how to work with data provided by a stream. Say you have a class that gives you a stream that kicks out a new integer once per second: 1, 2, 3, 4, 5…</p><p>You can use the <a href="https://api.dart.dev/stable/dart-async/Stream/listen.html">listen()</a> method to subscribe to the stream. The only required parameter is a function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c31dc00c60729231ff711a1f2c5a7c06/href">https://medium.com/media/c31dc00c60729231ff711a1f2c5a7c06/href</a></iframe><p>Every time a new value is emitted by the stream, the function gets called and prints the value:</p><pre>Data: 1<br>Data: 2<br>Data: 3<br>Data: 4<br>...</pre><p>That’s how listen() works.</p><blockquote><strong>Important:</strong> By default, streams are set up for single subscription. They hold onto their values until someone subscribes, and they only allow a single listener for their entire lifespan. If you try to listen to a stream twice, you’ll get an exception.</blockquote><blockquote>Fortunately Dart also offers broadcast streams. You can use the <a href="https://api.dart.dev/stable/dart-async/Stream/asBroadcastStream.html">asBroadcastStream()</a> method to make a broadcast stream from a single subscription one. Broadcast streams work the same as single subscription streams, but they can have multiple listeners, and if nobody’s listening when a piece of data is ready, that data is tossed out.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be6e85178bdfcd755067c7a16de5b022/href">https://medium.com/media/be6e85178bdfcd755067c7a16de5b022/href</a></iframe><p>Let’s go back to that first listen() call, because there are a couple more things to talk about.</p><p>As we mentioned earlier, streams can produce errors just like futures can. By adding an onError function to the listen() call, you can catch and process any error.</p><p>There’s also a cancelOnError property that’s true by default, but can be set to false to keep the subscription going even after an error.</p><p>And you can add an onDone function to execute some code when the stream is finished sending data, such as when a file has been completely read.</p><p>With all four of those parameters combined — onError, onDone, cancelOnError, and the required parameter (onData) — you can be ready in advance for whatever happens.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dea319494190bd75b912520147b65906/href">https://medium.com/media/dea319494190bd75b912520147b65906/href</a></iframe><blockquote><strong>Tip:</strong> The little subscription object that listen() returns has some useful methods of its own. It’s a <a href="https://api.dart.dev/stable/dart-async/StreamSubscription-class.html"><em>StreamSubscription</em></a>, and you can use it to pause, resume, and even cancel the flow of data.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/520a9f66cf6b442e8cbcd16bc03dc7b1/href">https://medium.com/media/520a9f66cf6b442e8cbcd16bc03dc7b1/href</a></iframe><h3>Using and manipulating streams</h3><p>Now that you know how to use listen() to subscribe to a stream and receive data events, we can talk about what makes streams really cool: manipulating them. Once you’ve got data in a stream, a lot of operations become fluent and elegant.</p><p>Going back to that number stream from earlier, we can use a method called <a href="https://api.dart.dev/stable/dart-async/Stream/map.html">map()</a> to take each value from the stream and convert it on the fly into something else. Give map() a function to do the conversion, and it returns a new stream, typed to match the return value of the function. Instead of a stream of ints, you now have a stream of strings. You can throw a listen() call on the end, give it the print() function, and now you’re printing strings directly off the stream, asynchronously, as they arrive.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ac03783e253fb674f00ca75a2cdf722/href">https://medium.com/media/6ac03783e253fb674f00ca75a2cdf722/href</a></iframe><p>There are a ton of methods that you can chain up like this. If you only want to print the even numbers, for example, you can use <a href="https://api.dart.dev/stable/dart-async/Stream/where.html">where()</a> to filter the stream. Give it a test function that returns a boolean for each element, and it returns a new stream that only includes values that pass the test.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8f291bde6b2e14f0acd17743cecf36b3/href">https://medium.com/media/8f291bde6b2e14f0acd17743cecf36b3/href</a></iframe><p>The <a href="https://api.dart.dev/stable/dart-async/Stream/distinct.html">distinct()</a> method is another good one. If you have an app that uses a Redux store, that store emits new app state objects in an onChange stream. You can use map() to convert that stream of state objects to a stream of view models for one part of the app. Then you can use the distinct() method to get a stream that filters out consecutive identical values (in case the store kicks out a change that doesn’t affect the subset of data in the view model). Then you can listen and update the UI whenever you get a new view model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a41b8d1210d6b2168bbbb8d194aea8ba/href">https://medium.com/media/a41b8d1210d6b2168bbbb8d194aea8ba/href</a></iframe><p>There are a bunch of additional methods built into Dart that you can use to shape and modify your streams. Plus, when you’re ready for even more advanced stuff, there’s the <a href="https://pub.dev/packages/async">async package</a> maintained by the Dart team and available on <a href="https://pub.dev/">pub.dev</a>. It has classes that can merge two streams together, cache results, and perform other types of stream-based wizardry.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WTHZRJjgF4qQvSDvY0Z9ow.png" /><figcaption>Try the async package for more stream-based wizardry.</figcaption></figure><p>For even more stream magic, take a look at the <a href="https://pub.dev/packages/stream_transform">stream_transform package</a>.</p><h3>Creating streams</h3><p>One advanced topic deserves a mention here, and that’s how to create streams of your own. Just like with futures, most of the time you’re going to be working with streams created for you by network libraries, file libraries, state management, and so on. But you can make your own as well, using a <a href="https://api.dart.dev/stable/dart-async/StreamController-class.html">StreamController</a>.</p><p>Let’s go back to that NumberCreator we’ve been using so far. Here’s the actual code for it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e4d50381bdf969e768232b9fa01a804/href">https://medium.com/media/7e4d50381bdf969e768232b9fa01a804/href</a></iframe><p>As you can see, it keeps a running count, and it uses a timer to increment that count each second. The interesting bit, though, is the stream controller.</p><p>A StreamController creates a brand new stream from scratch, and gives you access to both ends of it. There’s the stream end itself, where data arrives. (We’ve been using that one throughout this article.)</p><pre>Stream&lt;int&gt; get stream =&gt; _controller.stream;</pre><p>Then there’s the sink end, which is where new data gets added to the stream:</p><pre>_controller.sink.add(_count);</pre><p>NumberCreator here uses both of them. When the timer goes off, it adds the latest count to the controller’s sink, and then it exposes the controller’s stream with a public property so other objects can subscribe to it.</p><h3>Building Flutter widgets using streams</h3><p>Now that we’ve covered creating, manipulating, and listening to streams, let’s talk about how to put them to work building widgets in Flutter.</p><p>If you saw the previous video on futures, you might remember <a href="https://api.flutter.dev/flutter/widgets/FutureBuilder-class.html">FutureBuilder</a>. You give it a future and a builder method, and it builds widgets based on the state of the future.</p><p>For streams, there’s a similar widget called <a href="https://api.flutter.dev/flutter/widgets/StreamBuilder-class.html">StreamBuilder</a>. Give it a stream and a builder method, and it will rebuild its children whenever a new value is emitted by the stream.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a05ff211a85991d373ff0849f0de937/href">https://medium.com/media/6a05ff211a85991d373ff0849f0de937/href</a></iframe><p>The snapshot parameter is an <a href="https://api.flutter.dev/flutter/widgets/AsyncSnapshot-class.html">AsyncSnapshot</a>, just like with FutureBuilder. You can check its connectionState property to see if the stream hasn’t yet sent any data or if it’s completely finished. You can use the hasError property to see if the latest value is an error. And, of course, you can handle data values.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/07b72fea9c66c729c75471dbbeeb3991/href">https://medium.com/media/07b72fea9c66c729c75471dbbeeb3991/href</a></iframe><p>The main thing is just to make sure your builder knows how to handle all the possible states of the stream. Once you’ve got that, it can react to whatever the stream does.</p><h3>Summary</h3><p>This article talked about what streams represent, how you get values from a stream, ways to manipulate those values, and how StreamBuilder helps you use stream values in a Flutter app.</p><p>You can learn more about streams from the Dart and Flutter documentation:</p><ul><li>On <a href="https://dart.dev/">dart.dev</a>, see the <a href="https://dart.dev/tutorials/language/streams">streams tutorial</a>, the <a href="https://dart.dev/tutorials/server/cmdline">command-line app tutorial</a>, and the <a href="https://dart.dev/guides/libraries/library-tour#stream">stream section</a> of the library tour.</li><li>On <a href="https://flutter.dev/">flutter.dev</a>, see <a href="https://flutter.dev/docs/cookbook/networking/web-sockets">Work with WebSockets</a>, which features an example that uses StreamBuilder.</li></ul><p>Or go on to the next video in the <em>Asynchronous Programming in Dart </em>series. It talks about async and await, which are two keywords that Dart offers to help you keep your asynchronous code tight and easy to read.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FSmTCmDMi4BY%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DSmTCmDMi4BY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FSmTCmDMi4BY%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/924c442a7c91b7366476ddd092178bfe/href">https://medium.com/media/924c442a7c91b7366476ddd092178bfe/href</a></iframe><p><em>Big thanks to Andrew Brogdon, who created the video that this article is based on.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*Q2-Ac9rjIDSuXzbrQqGkVA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2569a993324d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/dartlang/dart-asynchronous-programming-streams-2569a993324d">Dart asynchronous programming: Streams</a> was originally published in <a href="https://medium.com/dartlang">Dart</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dart asynchronous programming: Futures]]></title>
            <link>https://medium.com/dartlang/dart-asynchronous-programming-futures-96937f831137?source=rss-fe67f3a27347------2</link>
            <guid isPermaLink="false">https://medium.com/p/96937f831137</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[asynchronous-programming]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[dartlang]]></category>
            <dc:creator><![CDATA[Kathy Walrath]]></dc:creator>
            <pubDate>Wed, 18 Sep 2019 14:01:03 GMT</pubDate>
            <atom:updated>2019-09-18T14:01:03.753Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*G4044qvxp8yBjmGVHVLEyw.png" /><figcaption>Many asynchronous Dart APIs return futures.</figcaption></figure><p>One of the most basic APIs that Dart has for asynchronous programming is <em>futures — </em>objects of type <a href="https://api.dartlang.org/stable/dart-async/Future-class.html">Future</a>. For the most part, Dart’s futures are very similar to the <em>future</em> or <em>promise</em> APIs found in other languages.</p><p>This article discusses the concepts behind Dart futures and tells you how to use the Future API. It also discusses the Flutter FutureBuilder widget, which helps you update a Flutter UI asynchronously, based on the state of a future.</p><p>Thanks to Dart language features like <a href="https://dart.dev/codelabs/async-await">async-await</a>, you might never need to use the Future API directly. But you’re almost certain to encounter futures in your Dart code. And you might want to <em>create</em> futures or <em>read</em> code that uses the Future API.</p><blockquote>This article is the second one based on the <em>Flutter in Focus</em> video series <em>Asynchronous Programming in Dart</em>. The first article, <a href="https://medium.com/dartlang/dart-asynchronous-programming-isolates-and-event-loops-bffc3e296a6a">Isolates and event loops</a>, covered the foundations of Dart’s support for background work.</blockquote><blockquote>If you prefer to learn by watching or listening, everything in this article is covered in the following video<em>.</em></blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FOTS-ap9_aXc%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DOTS-ap9_aXc&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FOTS-ap9_aXc%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b6cf4ee42282247c713fd0c0da5298c/href">https://medium.com/media/8b6cf4ee42282247c713fd0c0da5298c/href</a></iframe><p>You can think of futures as little gift boxes for data. Somebody hands you one of these gift boxes, which starts off closed. A little while later the box pops open, and inside there’s either a value or an error.</p><p>So a future can be in one of 3 states:</p><ol><li><strong>Uncompleted:</strong> The gift box is closed<em>.</em></li><li><strong>Completed with a value:</strong> The box is open, and your gift (data) is ready.</li><li><strong>Completed with an error:</strong> The box is open, but something went wrong.</li></ol><p>Most of the code you’re about to see revolves around dealing with these three states. You receive a future, and you need to decide what to do until the box opens, what to do when it opens with a value, and what to do if there’s an error. You’ll see that 1–2–3 pattern a lot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/1*UD63BMoIBmzoA6jo3LjCCg.png" /><figcaption>The 3 states of a future</figcaption></figure><p>You might remember the event loop (pictured below) from our <a href="https://medium.com/dartlang/dart-asynchronous-programming-isolates-and-event-loops-bffc3e296a6a">article about the Dart event loop</a>. A good thing to know about futures is that they’re really just an API built to make using the event loop easier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/0*xlxALlxjazVifRep.png" /><figcaption>The Dart event loop processes one event at a time.</figcaption></figure><p>The Dart code you write is executed by a single thread. The whole time your app is running, that one little thread just keeps going around and around, picking up events from the event queue and processing them.</p><p>Say you have some code for a download button (implemented below as a RaisedButton). The user taps, and your button starts downloading a picture.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d117128d4388430b3f161a8970cc27a0/href">https://medium.com/media/d117128d4388430b3f161a8970cc27a0/href</a></iframe><p>First the tap event occurs. The event loop gets the event, and it calls your tap handler (which you set using the onPressed parameter to the RaisedButton constructor). Your handler uses the http library to make a request (http.get()), and it gets a future in return (myFuture).</p><p>So now you’ve got your little box, myFuture. It starts off closed. To register a callback for when it opens, you use then().</p><p>Once you have your gift box, you wait. Maybe some other events come in, the user does some stuff, and your little box just sits there while the event loop keeps going around.</p><p>Eventually, data for the image is downloaded, and the http library says, “Great! I’ve got this future right here.” It puts the data in the box and pops it open, which triggers your callback.</p><p>Now that little piece of code you handed to then() executes, and it displays the image.</p><p>Throughout that process, your code never had to touch the event loop directly. It didn’t matter what else was going on, or what other events came in. All you needed to do was get the future from the http library, and then say what to do when the future completed.</p><p>In real code, you’d also take care of errors. We’ll show you how to do that a little later.</p><p>Let’s take a closer look at the Future API, some of which you just saw in use.</p><p>OK, first question: how do you get an instance of a Future? Most of the time, you don’t create futures directly. That’s because many of the common asynchronous programming tasks already have libraries that generate futures for you.</p><p>For example, network communication returns a future:</p><pre>final myFuture = http.get(&#39;http://example.com&#39;);</pre><p>Getting access to shared preferences also returns a future:</p><pre>final myFuture = SharedPreferences.getInstance();</pre><p>But you can also use Future constructors to create futures.</p><h3>Future constructors</h3><p>The simplest constructor is <a href="https://api.dartlang.org/stable/dart-async/Future/Future.html">Future()</a>, which takes a function and returns a future that matches the function’s return type. Later the function runs asynchronously, and the future completes with the function’s return value. Here’s an example of using Future():</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e27a259c2540f79cd29b55eb1f790e92/href">https://medium.com/media/e27a259c2540f79cd29b55eb1f790e92/href</a></iframe><p>Let’s add a couple of print statements to make the asynchronous part clear:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9f21b9217f909011fb1789ff165ae78a/href">https://medium.com/media/9f21b9217f909011fb1789ff165ae78a/href</a></iframe><p>If you run that code in DartPad (<a href="https://dartpad.dev/">dartpad.dev</a>), the entire main function finishes before the function given to the Future() constructor. That’s because the Future() constructor just returns an uncompleted future at first. It says, “Here’s this box. You hold onto that for now, and later I’ll go run your function and put some data in there for you.” Here’s the output of the preceding code:</p><pre>Done with main().<br>Creating the future.</pre><p>Another constructor, <a href="https://api.dartlang.org/stable/dart-async/Future/Future.value.html">Future.value()</a>, is handy when you already know the value for the future. This constructor is useful when you’re building services that use caching. Sometimes you already have the value you need, so you can pop it right in there:</p><pre>final myFuture = Future.value(12);</pre><p>The Future.value() constructor has a counterpart for completing with an error. It’s called <a href="https://api.dartlang.org/stable/dart-async/Future/Future.error.html">Future.error()</a>, and it works essentially the same way, but takes an error object and an optional stacktrace:</p><pre>final myFuture = Future.error(ArgumentError.notNull(&#39;input&#39;));</pre><p>The handiest future constructor is probably <a href="https://api.dartlang.org/stable/dart-async/Future/Future.delayed.html">Future.delayed()</a>. It works just like Future(), except that it waits for a specified length of time before running the function and completing the future.</p><p>One way to use Future.delayed() is when you’re creating mock network services for testing. If you need to make sure your loading spinner displays correctly, a delayed future is your friend.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b436044f5e815fb6fae7547737bdefa/href">https://medium.com/media/5b436044f5e815fb6fae7547737bdefa/href</a></iframe><h3>Using futures</h3><p>Now that you know where futures come from, let’s talk about how to use them. As we mentioned earlier, using a future is mostly about accounting for the three states it can be in: uncompleted, completed with a value, or completed with an error.</p><p>The following code uses Future.delayed() to create a future that completes after 3 seconds with a value of 100.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab4bcdad8dbe7a1b5424537f1ae494c8/href">https://medium.com/media/ab4bcdad8dbe7a1b5424537f1ae494c8/href</a></iframe><p>When this code executes, main() runs from top to bottom, creating the future and printing “Waiting for a value…” That whole time, the future is uncompleted. It doesn’t complete for another 3 seconds.</p><p>To <em>use</em> the completed value, you can use <a href="https://api.dartlang.org/stable/dart-async/Future/then.html">then()</a>. That’s an instance method on each future that you can use to register a callback for when the future completes with a value. You give it a function that takes a single parameter matching the type of the future. Once the future completes with a value, your function is called with that value.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f988acb78c06b4f422eb91fc8a37698c/href">https://medium.com/media/f988acb78c06b4f422eb91fc8a37698c/href</a></iframe><p>Here’s the output of the preceding code:</p><pre>Waiting for a value... <em>(3 seconds pass until callback executes)</em><br>The value is 100.</pre><p>In addition to executing your code, then() returns a future of its own, matching the return value of whatever function you give it. So if you need to make a couple of asynchronous calls, you can chain them together even if they have different return types.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5a6e0a91c6b445d288a0000afcca55b3/href">https://medium.com/media/5a6e0a91c6b445d288a0000afcca55b3/href</a></iframe><p>Back to our first example, what happens if that initial future doesn’t complete with a value — what if it completes with an error? The then() method expects a value. You need a way to register another callback in case of an error.</p><p>The answer is to use <a href="https://api.dartlang.org/stable/dart-async/Future/catchError.html">catchError()</a>. It works just like then(), except that it takes an error instead of a value, and it executes if the future completes with an error. Just like then(), the catchError() method returns a future of its own, so you can build a whole chain of then() and catchError()methods that wait on one another.</p><blockquote><strong>Note: </strong>You don’t need to call then() or catchError() if you use the async-await language feature. Instead, you await the completed value, and you use try-catch-finally to handle errors. For details, see the Dart language tour’s <a href="https://dart.dev/guides/language/language-tour#asynchrony-support">asynchrony support section</a>.</blockquote><p>Here’s an example of using catchError() to handle the case where a future completes with an error:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/db525189bde74549870e219535581770/href">https://medium.com/media/db525189bde74549870e219535581770/href</a></iframe><p>You can even give catchError() a test function to check the error before invoking the callback. You can have multiple catchError() functions this way, each one checking for a different kind of error. Here’s an example of specifying a test function, using the optional test parameter to catchError():</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe5017c41b1935118b8bac05a0e78bb0/href">https://medium.com/media/fe5017c41b1935118b8bac05a0e78bb0/href</a></iframe><p>Now that you’ve gotten this far, hopefully you can see how the three states of a future are often reflected by the structure of the code. There are three blocks in the preceding example:</p><ol><li>The first block creates an uncompleted future.</li><li>Then there’s a function to call if the future completes with a value.</li><li>Then there’s another function to call if the future completes with an error.</li></ol><p>There’s one more method you might want to use: <a href="https://api.dartlang.org/stable/dart-async/Future/whenComplete.html">whenComplete()</a>. You can use it to execute a function when the future is completed, no matter whether it’s with a value or an error.</p><p>It’s kind of like the <em>finally</em> block in a try-catch-finally. There’s code executed if everything goes right, code for an error, and code that runs no matter what.</p><h3>Using futures in Flutter</h3><p>So that’s how you create futures, and a bit about how you can use their values. Now let’s talk putting them to work in Flutter.</p><p>Say you have a network service that’s going to return some JSON data, and you want to display that data. You could create a <a href="https://api.flutter.dev/flutter/widgets/StatefulWidget-class.html">StatefulWidget</a> that creates the future, checks for completion or error, calls setState(), and generally handles all the wiring manually.</p><p>Or you can use <a href="https://api.flutter.dev/flutter/widgets/FutureBuilder-class.html">FutureBuilder</a>. It’s a widget that comes with the Flutter SDK. You give it a future and a builder function, and it automatically rebuilds its children when the future completes.</p><p>The FutureBuilder widget works by calling its builder function, which takes a context and a snapshot of the current state of the future.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4d061e92c50ac8668b523456fd22ca3/href">https://medium.com/media/d4d061e92c50ac8668b523456fd22ca3/href</a></iframe><p>You can check the snapshot to see whether the future completed with an error:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ec30bac06a737610df8007c8a790080b/href">https://medium.com/media/ec30bac06a737610df8007c8a790080b/href</a></iframe><p>Otherwise you can check the hasData property to see if it completed with a value:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/822acd24d8ce82d850f9478bfc202de2/href">https://medium.com/media/822acd24d8ce82d850f9478bfc202de2/href</a></iframe><p>If neither hasError nor hasData is true, then you know you’re still waiting, and you can output something for that as well.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2dcbbe30464eec59149d857caf678ea8/href">https://medium.com/media/2dcbbe30464eec59149d857caf678ea8/href</a></iframe><p>Even in Flutter code, you can see how those three states keep popping up: uncompleted, completed with value, and completed with error.</p><h3>Summary</h3><p>This article talked about what futures represent and how you can use the Future and FutureBuilder APIs to create futures and use their completed values.</p><p>If you’d like to learn more about using futures—with the option of using runnable examples and interactive exercises to test your understanding—check out the asynchronous codelab on <a href="https://dart.dev/codelabs/async-await">futures, async, and await</a>.</p><p>Or go on to the next video in the <em>Asynchronous Programming in Dart </em>series. It talks about <em>streams</em>, which are a lot like futures in that they can provide either values or errors. But where futures just give you one result and stop, streams just keep right on going.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FnQBpOIHE4eE%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DnQBpOIHE4eE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FnQBpOIHE4eE%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/19f7572c0ed7e65b2b45fc00703972c6/href">https://medium.com/media/19f7572c0ed7e65b2b45fc00703972c6/href</a></iframe><p><em>Big thanks to Andrew Brogdon, who created the video that this article is based on.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96937f831137" width="1" height="1" alt=""><hr><p><a href="https://medium.com/dartlang/dart-asynchronous-programming-futures-96937f831137">Dart asynchronous programming: Futures</a> was originally published in <a href="https://medium.com/dartlang">Dart</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dart nullability syntax decision: a?[b] or a?.[b]]]></title>
            <link>https://medium.com/dartlang/dart-nullability-syntax-decision-a-b-or-a-b-d827259e34a3?source=rss-fe67f3a27347------2</link>
            <guid isPermaLink="false">https://medium.com/p/d827259e34a3</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[dartlang]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[syntax]]></category>
            <dc:creator><![CDATA[Kathy Walrath]]></dc:creator>
            <pubDate>Mon, 26 Aug 2019 17:19:59 GMT</pubDate>
            <atom:updated>2021-03-29T18:28:13.617Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Update (3/2021): Thanks to your feedback, the Dart team <a href="https://github.com/dart-lang/language/issues/376#issuecomment-576924506">decided to use the a?[b] syntax</a>.</blockquote><p>Dart is <a href="https://github.com/dart-lang/language/issues/110">in the process</a> of redesigning its type system so that individual types will be either <em>nullable</em> (expressions of that type can have the value null) or <em>non-nullable</em>. Later this year we’ll tell you more about the timeline and roll-out process, but eventually Dart code will be non-nullable by default (<em>NNBD</em>), and you’ll have to use special syntax to say that a type permits null values.</p><p>For example, to declare that an integer can be null, you’ll need to add a ? after the type:</p><pre>int? someInt; // someInt can be null.</pre><p>That question mark syntax might be familiar if you’ve seen Kotlin, Swift, or C# code. But some things are different — notably the subscript ([]) operator, which you most often see used for list or array access. C# and Swift use ?[]. The current plan for Dart (and, by the way, for <a href="https://github.com/tc39/proposal-optional-chaining#syntax">ECMAScript</a>) is to use ?.[] instead:</p><pre>e1?.[e2] // null if e1 is null; otherwise it’s e1[e2]</pre><p>This article takes you behind the scenes to explain the reasoning behind this decision, and to encourage you to weigh in with your thoughts and suggestions. Most of this content is based on a <a href="https://github.com/dart-lang/language/issues/376#issuecomment-497121257">comment by Bob Nystrom</a> (<a href="https://github.com/munificent">munificent</a>) on language issue <a href="https://github.com/dart-lang/language/issues/376">#376</a>, which summarizes a discussion between Bob and the owner of the NNBD specification, Leaf Petersen (<a href="https://github.com/leafpetersen">leafpetersen</a>).</p><h3><strong>Why use a dot?</strong></h3><p>Both options for [] have advantages.</p><p>e1?[e2]:</p><ul><li>Follows C# and Swift</li><li>Is concise</li><li>Is similar to the syntax for the ! operator (which you’ll be able to add after an expression to say that its value isn’t null, even though it has a nullable type): e1![e2]</li></ul><p>e1?.[e2]:</p><ul><li>Is similar to cascade syntax:<br>e1..[e2] // cascade syntax<br>e1?..[e2] // null-aware cascade syntax</li><li>Is similar to other null-aware method syntax: e1?.e2()</li><li>Extends naturally to other operators</li><li>Avoids the ambiguity in the following code: { e1 ? [e2] : e3 }</li></ul><p>We spent a while trying to come up with ways to avoid the ambiguity of ?[. The problem is that you can’t tell whether code like { e1 ? [e2] : e3 } is a <a href="https://dart.dev/guides/language/language-tour#sets">set literal</a> containing the result of a conditional expression, or a <a href="https://dart.dev/guides/language/language-tour#maps">map literal</a> containing the result of a null-aware subscript.</p><p>If we add parentheses to make that code unambiguous, we could either choose to add them around the entire expression — { (e1 ? [e2] : e3) } — making it unambiguously a set literal. Or we could add them around the first part — { (e1 ? [e2]) : e3 } — making it unambiguously a map literal. But in the absence of parentheses, the parser doesn’t know what to do.</p><p>There are various solutions to this ambiguity, but none of them seem very satisfying. One approach is to rely on whitespace to distinguish between the options. In this approach, you always treat e1 ? [e2] as the start of a conditional expression, because there is a space between the ? and the [. And you always treat e1?[e2] as a null-aware subscript because there’s no space between those two tokens. But relying on whitespace can really harm the user experience.</p><p>In theory, relying on whitespace isn’t a problem in formatted code. But many users write unformatted Dart code as an input to the formatter. And that input format would thus become more whitespace sensitive and brittle in this corner of the language. So far, those kind of corners are very rare in Dart, which is a nice feature. (One such corner is that — — a and --a are both valid but mean different things.)</p><p>Ignoring the ambiguity, there’s another reason for using the dot: if we add null-aware forms for other operators — e1?.+(e2), etc. — we’ll probably want to require the dot, in which case requiring it for subscript is consistent with that future.</p><p>Another addition we’ve discussed for NNBD is a null-aware call syntax. If we don’t require a dot there, it has the exact same ambiguity problem:</p><pre>var wat = { e1?(e2):e3 }; // Map or set?</pre><p>Whatever fix we come up with for the ?[, we’ll also have to apply to ?(.</p><p>Finally, consider this example of chaining the subscript:</p><pre>someJson?[recipes]?[2]?[ingredients]?[pepper]</pre><p>To our eyes, that doesn’t look very good. It scans less like a method chain and more like some combination of infix operators — a little like ??. Compare it to this code:</p><pre>someJson?.[recipes]?.[2]?.[ingredients]?.[pepper]</pre><p>Here, it’s more clearly a method chain. Communicating that visually is important too, because users need to quickly understand how much of an expression will get null-short-circuited.</p><p>Putting all of that together, it seems like we should use the ?.[ form for the following reasons:</p><ul><li>It avoids ambiguity problems. (The lexer already treats ?. as a single “null-aware” token.)</li><li>It extends naturally to a null-aware call.</li><li>It extends to other null-aware operators.</li><li>It leaves Dart a more robust input language to the formatter.</li><li>It looks pretty OK in a method chain.</li><li>It makes it visually clearer how much of a method chain may be short-circuited.</li></ul><h3>What do you think?</h3><p>We’re always interested in feedback and suggestions. The best way to give feedback on this syntax is to comment (or thumbs-up a comment) on <a href="https://github.com/dart-lang/language/issues/376">language issue #376</a>. While you’re at it, consider checking out all of the other cool language features we’re working on.</p><p>Here’s where you can find more information:</p><p>NNBD:</p><ul><li><a href="https://github.com/dart-lang/language/blob/master/accepted/future-releases/nnbd/feature-specification.md">Feature specification</a></li><li><a href="https://github.com/dart-lang/language/blob/master/accepted/future-releases/nnbd/roadmap.md">Roadmap</a></li><li><a href="https://github.com/dart-lang/language/issues?utf8=%E2%9C%93&amp;q=label%3Annbd">Issues</a></li></ul><p>Other Dart language changes and features:</p><ul><li><a href="https://github.com/dart-lang/language/projects/1">Status of language changes</a></li><li><a href="https://github.com/dart-lang/language/blob/master/doc/life_of_a_language_feature.md#dart-language-evolution-process">Language evolution process</a></li><li><a href="https://dart.dev/guides/language/spec">Dart language specification</a></li></ul><figure><img alt="An abbreviated code snippet that includes `String?`, `List&lt;String&gt;?`, and `return list?.[index]`." src="https://cdn-images-1.medium.com/max/513/1*se-VT1aPyHd3J2VYDzDW5g.png" /><figcaption>A function that accepts a null argument and can return null.</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d827259e34a3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/dartlang/dart-nullability-syntax-decision-a-b-or-a-b-d827259e34a3">Dart nullability syntax decision: a?[b] or a?.[b]</a> was originally published in <a href="https://medium.com/dartlang">Dart</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dart asynchronous programming: Isolates and event loops]]></title>
            <link>https://medium.com/dartlang/dart-asynchronous-programming-isolates-and-event-loops-bffc3e296a6a?source=rss-fe67f3a27347------2</link>
            <guid isPermaLink="false">https://medium.com/p/bffc3e296a6a</guid>
            <category><![CDATA[event-loop]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[dartlang]]></category>
            <category><![CDATA[asynchronous-programming]]></category>
            <dc:creator><![CDATA[Kathy Walrath]]></dc:creator>
            <pubDate>Thu, 25 Jul 2019 16:08:10 GMT</pubDate>
            <atom:updated>2020-01-23T22:34:24.421Z</atom:updated>
            <content:encoded><![CDATA[<p>Dart, despite being a single-threaded language, offers support for futures, streams, background work, and all the other things you need to write in a modern, asynchronous, and (in the case of Flutter) reactive way. This article covers the foundations of Dart’s support for background work: <em>isolates</em> and <em>event loops</em>.</p><p>If you prefer to learn by watching or listening, everything in this article is covered in the following video, which is part of the <em>Flutter in Focus</em> video series <em>Asynchronous Programming in Dart:</em></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fvl_AaCgudcY%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dvl_AaCgudcY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fvl_AaCgudcY%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/e80af6e037b2f07d9cd64134c3a9383c/href">https://medium.com/media/e80af6e037b2f07d9cd64134c3a9383c/href</a></iframe><p>Still here? Let’s talk about isolates.</p><h3>Isolates</h3><p>An <em>isolate</em> is what all Dart code runs in. It’s like a little space on the machine with its own, private chunk of memory and a single thread running an event loop.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/278/1*xtjhmzoLQEmh7Od1BkroVg.png" /><figcaption>An isolate has its own memory and a single thread of execution that runs an event loop.</figcaption></figure><p>In a lot of other languages like C++, you can have multiple threads sharing the same memory and running whatever code you want. In Dart, though, each thread is in its own isolate with its own memory, and the thread just processes events (more on that in a minute).</p><p>Many Dart apps run all their code in a single isolate, but you can have more than one if you need it. If you have a computation to perform that’s so enormous it could cause you to drop frames if it were run in the main isolate, then you can use <a href="https://api.dartlang.org/stable/dart-isolate/Isolate/spawn.html">Isolate.spawn()</a> or <a href="https://flutter.dev/docs/cookbook/networking/background-parsing#4-move-this-work-to-a-separate-isolate">Flutter’s compute() function</a>. Both of those functions create a separate isolate to do the number crunching, leaving your main isolate free to — say— rebuild and render the widget tree.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*MnJQG2bdbcqmEwu1lSL52Q.png" /><figcaption>Two isolates, each with its own memory and thread of execution.</figcaption></figure><p>The new isolate gets its own event loop and its own memory, which the original isolate — even though it’s the parent of this new one — isn’t allowed to access. That’s the source of the name <em>isolate</em>: these little spaces are kept <em>isolated</em> from one another.</p><p>In fact, the only way that isolates can work together is by passing messages back and forth. One isolate sends a message to the other, and the receiving isolate processes that message using its event loop.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*kxDfLtL2ySN1yiY1nmcTrA.png" /><figcaption>Isolates can send messages to other isolates.</figcaption></figure><p>This lack of shared memory might sound kind of strict, especially if you’re coming from a language like Java or C++, but it has some key benefits for Dart coders.</p><p>For example, memory allocation and garbage collection in an isolate don’t require locking. There’s only one thread, so if it’s not busy, you know the memory isn’t being mutated. That works out well for Flutter apps, which sometimes need to build up and tear down a bunch of widgets quickly.</p><h3>Event loops</h3><p>Now that you’ve had a basic introduction to isolates, let’s dig in to what really makes asynchronous code possible: the <em>event loop</em>.</p><p>Imagine the life of an app stretched out on a timeline. The app starts, the app stops, and in between a bunch of events occur — I/O from the disk, finger taps from the user… all kinds of stuff.</p><p>Your app can’t predict when these events will happen or in what order, and it has to handle all of them with a single thread that never blocks. So, the app runs an event loop. It grabs the oldest event from its event queue, processes it, goes back for the next one, processes it, and so on, until the event queue is empty.</p><p>The whole time the app is running — you’re tapping on the screen, things are downloading, a timer goes off — that event loop is just going around and around, processing those events one at a time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*t-mHg6JrdkKCs65UvD70-Q.png" /><figcaption>The event loop processes one event at a time.</figcaption></figure><p>When there’s a break in the action, the thread just hangs out, waiting for the next event. It can trigger the garbage collector, get some coffee, whatever.</p><p>All of the high-level APIs and language features that Dart has for asynchronous programming — futures, streams, async and await — they’re all built on and around this simple loop.</p><p>For example, say you have a button that initiates a network request, like this one:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5f48733b8fa51f699640162252d2c611/href">https://medium.com/media/5f48733b8fa51f699640162252d2c611/href</a></iframe><p>When you run your app, Flutter builds the button and puts it on screen. Then your app waits.</p><p>Your app’s event loop just sort of idles, waiting for the next event. Events that aren’t related to the button might come in and get handled, while the button sits there waiting for the user to tap on it. Eventually they do, and a tap event enters the queue.</p><p>That event gets picked up for processing. Flutter looks at it, and the rendering system says, “Those coordinates match the raised button,” so Flutter executes the onPressed function. That code initiates a network request (which returns a future) and registers a completion handler for the future by using the then() method.</p><p>That’s it. The loop is finished processing that tap event, and it’s discarded.</p><p>Now, onPressed is a property of <a href="https://api.flutter.dev/flutter/material/RaisedButton-class.html">RaisedButton</a>, and the network event uses a callback for a <a href="https://api.dart.dev/stable/dart-async/Future-class.html">future</a>, but both of those techniques are doing the same basic thing. They’re both a way to tell Flutter, “Hey, later on, you might see a particular type of event come in. When you do, please execute this piece of code.”</p><p>So, onPressed is waiting for a tap, and the future is waiting for network data, but from Dart’s perspective, those are both just events in the queue.</p><p>And that’s how asynchronous coding works in Dart. Futures, streams, async and await — these APIs are all just ways for you to tell Dart’s event loop, “Here’s some code, please run it later.”</p><p>If we look back at the code example, you can now see exactly how it’s broken up into blocks for particular events. There’s the initial build (1), the tap event (2), and the network response event (3).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ae7636cc12b748fde92de79364c9219/href">https://medium.com/media/4ae7636cc12b748fde92de79364c9219/href</a></iframe><p>After you get used to working with asynchronous code, you’ll start recognizing these patterns all over the place. Understanding the event loop is going to help as you move on to the higher level APIs.</p><h3>Summary</h3><p>We took a quick look at isolates, the event loop, and the foundation of asynchronous coding in Dart. If you’re looking for more details such as how the microtask queue works, see the out-of-date, archived-but-still-beloved article <a href="https://web.archive.org/web/20170704074724/https://webdev.dartlang.org/articles/performance/event-loop">The Event Loop and Dart</a>.</p><p>To learn more about asynchrony in Dart, check out the next article in this series, <a href="https://medium.com/dartlang/dart-asynchronous-programming-futures-96937f831137">Dart asynchronous programming: Futures</a>.</p><p><em>Big thanks to Andrew Brogdon, who created the video that this article is based on.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bffc3e296a6a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/dartlang/dart-asynchronous-programming-isolates-and-event-loops-bffc3e296a6a">Dart asynchronous programming: Isolates and event loops</a> was originally published in <a href="https://medium.com/dartlang">Dart</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>