<?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 Marya Belanger on Medium]]></title>
        <description><![CDATA[Stories by Marya Belanger on Medium]]></description>
        <link>https://medium.com/@mbelanger_65682?source=rss-ae996dbdd76e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dvfKkfTnezv7BhXgB51pGA.png</url>
            <title>Stories by Marya Belanger on Medium</title>
            <link>https://medium.com/@mbelanger_65682?source=rss-ae996dbdd76e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 08:17:36 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mbelanger_65682/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[Announcing Dart 3.7]]></title>
            <link>https://medium.com/dartlang/announcing-dart-3-7-bf864a1b195c?source=rss-ae996dbdd76e------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf864a1b195c</guid>
            <category><![CDATA[announcements]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[dartlang]]></category>
            <category><![CDATA[dart]]></category>
            <dc:creator><![CDATA[Marya Belanger]]></dc:creator>
            <pubDate>Wed, 12 Feb 2025 19:10:27 GMT</pubDate>
            <atom:updated>2025-02-12T19:13:26.487Z</atom:updated>
            <content:encoded><![CDATA[<p>It’s a new year, and time for a new Dart stable release. Welcome to Dart 3.7!</p><p>The theme for this release is <em>developer productivity</em>. We’ve made the Dart language more consistent by tweaking how it handles wildcard variables. There’s also a brand new style in the Dart formatter, new quick fixes and lints in the analyzer, and several cool new features on pub.dev. Let’s get into the details!</p><figure><img alt="Announcing Dart 3.7" src="https://cdn-images-1.medium.com/max/1024/1*tdCaUfGrIk42FIuu2qs9Yw.gif" /><figcaption>Announcing Dart 3.7</figcaption></figure><h3>Macros update</h3><p>We recently posted updates in the <a href="https://github.com/dart-lang/language/issues/1482#issuecomment-2622895490">issue tracker</a>, as well as a <a href="https://medium.com/dartlang/an-update-on-dart-macros-data-serialization-06d3037d4f12">blog post</a>, stating that we’re stopping work on our experimental macros feature. We’d like to thank the community for being so understanding of this unfortunate outcome.</p><p>With this change, however, the team gains back some capacity to invest in other valuable developments. We’re already looking into <a href="https://github.com/dart-lang/build/issues/3800">improvements to build_runner performance</a>, we still expect to launch the <a href="https://github.com/dart-lang/language/blob/main/working/augmentation-libraries/feature-specification.md">augmentations language feature</a> (perhaps in a slightly different form), and we hope to find new and more direct ways for supporting modeling data and handling <a href="https://github.com/dart-lang/language/issues/4232">serialization and deserialization</a> (to and from JSON, for example).</p><h3>Wildcard variables language feature</h3><p>Local variables and parameters named _ are now what functional languages call “wildcards”. This means the name is a placeholder and declares no actual variable.</p><p>Currently in Dart, it’s common to use _ as the name of a callback parameter if the body of the callback doesn’t actually need to use the argument, like so:</p><pre>void announceCompletion(Future&lt;void&gt; future) {<br>  future.then((_) { // &lt;--<br>    print(&#39;Complete!&#39;);<br>  });<br>}</pre><p>But, if a callback has multiple parameters that you don’t need to use, you end up naming them _, __, ___, etc., because otherwise the names collide. Now, in Dart 3.7, parameters and local variables named _ don’t actually create a variable, so there is no possibility of name collision. You can use _ for multiple parameters, as in:</p><pre>void announceFailure(Future&lt;void&gt; future) {<br>  future.onError((_, _) { // &lt;--<br>    print(&#39;Error!&#39;);<br>  });<br>}</pre><p>If you have code that declares a parameter or variable named _ <em>and uses it</em>, that code will no longer work in Dart 3.7. For example:</p><pre>var [1, 2, 3].map((_) {<br>  return _.toString();<br>  //     ^ Error! Reference to unknown variable.<br>});</pre><p>You’ll have to rename the parameter or local variable in this situation. This language change only applies to parameters and local variables (not top-level variables or members), so you can do this renaming without breaking your library’s public API.</p><p>Wildcard variables are a small feature that make the language more consistent. Variables named _ in <a href="https://dart.dev/language/patterns">patterns</a> have always behaved this way:</p><pre>var [_, _, third, _, _] = [1, 2, 3, 4, 5];<br>print(third); // Prints &quot;3&quot;.</pre><p>Now parameters and local variables behave the same way.</p><h3>New formatting style in the Dart formatter</h3><p>Dart 3.7 includes a re-written Dart formatter (dart format) with a <a href="https://github.com/dart-lang/dart_style/issues/1253">new formatting style</a>. The new style looks similar to the style you get when you add trailing commas to argument lists, except now the formatter will add and remove those commas for you. For example:</p><pre>// Old style:<br>void writeArgumentList(<br>    Token leftBracket, List&lt;AstNode&gt; elements, Token rightBracket) {<br>  writeList(<br>      leftBracket: leftBracket,<br>      elements,<br>      rightBracket: rightBracket,<br>      allowBlockArgument: true);<br>}<br><br>// New style:<br>void writeArgumentList(<br>  Token leftBracket,<br>  List&lt;AstNode&gt; elements,<br>  Token rightBracket,<br>) {<br>  writeList(<br>    leftBracket: leftBracket,<br>    elements,<br>    rightBracket: rightBracket,<br>    allowBlockArgument: true,<br>  );<br>}</pre><p>This is a large change both to the tool, the output it produces, and how it behaves. To make the transition as smooth as possible, the formatting style you get depends on the <a href="https://dart.dev/guides/language/evolution">language version</a> of the code you’re formatting. If the language version is 3.6 or earlier, the code is formatted with the old style. If it’s 3.7 or later, it gets the new style.</p><p>When you upgrade your package to use Dart 3.7 by bumping the SDK constraint in your package’s pubspec (and running dart pub get!), you are opting in to the new formatting style.</p><p>To determine the language version of each file it formats, dart format looks for a package_config.json. This means that <strong>you need to run </strong><strong>dart pub get before formatting code in your package</strong>. If you have format checks in your continuous integration server, make sure it runs dart pub get, too.</p><p>We don’t intend to support both styles indefinitely. At some point in the future, when most of the ecosystem is on 3.7 or later, support for the old style will be removed.</p><p>The new style includes some long-requested features:</p><ul><li><strong>Project-wide page width configuration.</strong> You can now configure your preferred formatting page width on a project-wide basis in your analysis_options.yaml file, like so:</li></ul><pre>    formatter:<br>      page_width: 123</pre><ul><li><strong>Opting out a region of code from formatting.</strong> You can use a pair of special marker comments to opt a region of code out of automated formatting:</li></ul><pre>    main() {<br>      // dart format off<br>      no   +   formatting     +     here;<br>      // dart format on<br>    }</pre><p>There is one <strong>breaking change</strong> as well. The formatter no longer supports dart format --fix. Instead, use dart fix to apply all the fixes that dart format could, and more.</p><p>You can find more details in the <a href="https://github.com/dart-lang/dart_style/blob/cea5a1a3e974c5065e6f4cc19b2838cd62448f0a/CHANGELOG.md#300">CHANGELOG</a> and <a href="https://github.com/dart-lang/dart_style/wiki/FAQ">FAQ</a>.</p><h3>Updated quick fixes and new lints in the Dart analyzer</h3><p>We’re always actively improving Dart to boost developer productivity, and that means improving the analyzer with new lints, quick fixes, and assists in Dart 3.7. One notable addition is the unnecessary_underscores lint, which supports the new wildcard variable feature.</p><p>Among the wide range of new quick fixes and assists Dart 3.7 includes are fixes for common issues like missing await keywords, incorrect import prefixes, and violations of lint rules like cascade_invocations. There are also handy assists for refactoring code, such as converting else blocks to else if and wrapping Flutter widgets with Expanded or Flexible.</p><p>You can find more details about all of these, and much more, in the full list of <a href="https://github.com/dart-lang/sdk/blob/master/CHANGELOG.md#analyzer-1">analyzer changes</a>.</p><h3>Moving forward on the Dart web platform</h3><p>A year ago, we introduced <a href="https://medium.com/dartlang/dart-3-3-325bf2bf6c13">new libraries and packages</a> for interoperating with JavaScript and browser APIs from Dart. Going forward, the primary JavaScript library is <a href="https://api.dart.dev/dart-js_interop/dart-js_interop-library.html">dart:js_interop</a>. For browser APIs, use <a href="https://pub.dev/packages/web">package:web</a>.</p><p>As part of our continued effort to move the Dart and Flutter ecosystems to WebAssembly-compatible APIs, we are deprecating the associated legacy APIs in the Dart SDK. Seven Dart SDK libraries are deprecated in the Dart 3.7 release:</p><ul><li>dart:html</li><li>dart:indexed_db</li><li>dart:js</li><li>dart:js_util</li><li>dart:web_audio</li><li>dart:web_gl</li></ul><p>We plan to remove these libraries at the end of 2025. You can learn about their replacements on the <a href="https://dart.dev/interop/js-interop">JavaScript interoperability page</a>.</p><h3>New productivity features on the pub.dev package site</h3><p>In December we launched <a href="https://medium.com/dartlang/announcing-dart-3-6-778dd7a80983">download counts for packages</a> on pub.dev. These show monthly downloads along with a small chart showing weekly downloads over time.</p><p>Today, we are extending that with support for viewing download counts per package version. It’s now possible to get an indication of how many consumers of a package have upgraded to the latest version (or just the latest major version). These insights are meant to help package authors gauge the value of back-porting fixes to older major versions of a package.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*67af_RLHqiWxsXXL" /><figcaption>Weekly downloads chart</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Cctb0O4F1D-0YYHY" /><figcaption>Weekly downloads chart</figcaption></figure><p><strong>Dark mode for pub.dev</strong></p><p>Dark mode for pub.dev has long been a <a href="https://github.com/dart-lang/pub-dev/issues/4416">popular request</a>, and as of today it’s now possible to toggle pub.dev to dark mode. This toggle affects both package pages and package API documentation hosted on pub.dev.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*j4Vh_XoLle5-RMQ2" /><figcaption>Dark mode for pub.dev</figcaption></figure><p><strong>Topics for pub.dev</strong></p><p>Last year, we launched support for <a href="https://pub.dev/topics">topics</a> on pub.dev. You can <a href="https://dart.dev/tools/pub/pubspec#topics">add topics</a> to your pubspec.yaml, and if you see related topics that should be merged you can propose <a href="https://github.com/dart-lang/pub-dev/blob/master/doc/topics.yaml">canonicalization</a> with a pull request.</p><p>Users browsing pub.dev can click on topics to browse related packages. We previously introduced the ability to search for topics on pub.dev, using <a href="https://pub.dev/help/search">search keywords</a> (like “topic:widget”), but finding these keywords has not always been easy. So, we’ve launched an IDE-like auto-completer for search keywords on pub.dev. You can trigger it by pressing ctrl+space, or automatically trigger it when you type a matching prefix like “topic:” or “license:”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kd0l2oZq_mg9g8YO" /><figcaption>Topics search keywords</figcaption></figure><h3>Wrap up</h3><p>That’s all we have today for Dart 3.7. As always, please let us know what you think! And don’t forget to check out the blog post for today’s <a href="https://medium.com/flutter/f90c380c2317">Flutter 3.29 release</a> as well. See you next time!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf864a1b195c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/dartlang/announcing-dart-3-7-bf864a1b195c">Announcing Dart 3.7</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[Announcing Dart 3.6]]></title>
            <link>https://medium.com/dartlang/announcing-dart-3-6-778dd7a80983?source=rss-ae996dbdd76e------2</link>
            <guid isPermaLink="false">https://medium.com/p/778dd7a80983</guid>
            <category><![CDATA[dartlang]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[dart]]></category>
            <dc:creator><![CDATA[Marya Belanger]]></dc:creator>
            <pubDate>Wed, 11 Dec 2024 20:20:13 GMT</pubDate>
            <atom:updated>2024-12-11T20:20:13.654Z</atom:updated>
            <content:encoded><![CDATA[<p>Welcome to Dart 3.6! Today is our last release of the year, alongside <a href="https://medium.com/flutter/whats-new-in-flutter-3-27-28341129570c">Flutter 3.27</a>. We’re excited to share a new feature in the language,<em> digit separators</em>. We also have several new features in the pub ecosystem: <em>pub download counts</em>, and the highly anticipated<em> pub workspaces</em>!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pojZOcfCeFztkEzK" /><figcaption>Dart 3.6</figcaption></figure><h3>Pub workspaces</h3><p>Pub now supports shared resolution between packages in a monorepo, or workspace. A workspace is a tightly related group of packages developed, resolved, and released together.</p><p>The pub workspaces feature ensures that packages in a monorepo share a consistent set of dependencies. This forces you to resolve dependency conflicts between your grouped packages <em>as they arise,</em> rather than facing confusion when you start using the packages..</p><p>The Flutter analyzer processes all of the packages in a pub workspace in a single analysis context, as opposed to the previous behavior of a separate context for each package. For large repositories, this can significantly reduce the amount of memory the Dart language server consumes, improving IDE performance.</p><p>To define a pub workspace, add the workspace field in the root pubspec.yaml file and list the related packages, as shown in the following example:</p><pre>name: _<br>publish_to: none<br>environment:<br>  sdk: ^3.6.0<br>workspace:<br>  - packages/helper<br>  - packages/client_package<br>  - packages/server_package</pre><p>Then run pub get anywhere in the repository to complete the mapping and remaining file management.</p><p>To use pub workspaces, all workspace packages (but not dependencies) must have an SDK version constraint of ^3.6.0 or greater.</p><p>For more information including fully detailed instructions and edge cases coverage, check out the <a href="https://dart.dev/go/pub-workspaces">Pub workspaces (monorepo support)</a> page.</p><h3>Pub download counts</h3><p>We listened to <a href="https://github.com/dart-lang/pub-dev/issues/2714">your requests</a> for more precise metrics on pub.dev, and now download counts are here! The download count replaces the previous “popularity score” on individual package pages. Along with the new metric, you will also find a sparkline chart on each page, showing weekly downloads over time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KJoC5ioNl7lXms0P" /><figcaption>A screenshot highlighting the new download count and sparkline graph on pub.dev</figcaption></figure><p>You can learn more about download counts in the <a href="https://pub.dev/help/scoring">pub.dev scoring documentation</a>.</p><h3>Digit separators</h3><p>The Dart language now allows underscores (_) as digit separators, which help make long number literals more readable. Multiple consecutive underscores indicate higher level grouping. Here are some examples of valid digit separator uses in Dart:</p><pre>1__000_000__000_000__000_000<br>0x4000_0000_0000_0000<br>0.000_000_000_01<br>0x00_14_22_01_23_45</pre><p>Remember, digit separators are valid only <em>between</em> digits, so literals like 100_, 0._000_1, or 1.2e_3 aren’t allowed. It’s also important to use digit separators consistently, so make sure digit groups are the same size between every level of groups.</p><p>To use digit separators, you’ll need to bump the minimum SDK in your package to 3.6.0 or greater.</p><h3>Closing</h3><p>That’s all for today. For the full story of what the Dart team has been up to this quarter, check out the <a href="https://github.com/dart-lang/sdk/blob/main/CHANGELOG.md#360">Changelog for 3.6.0</a>. And don’t forget to visit the <a href="https://medium.com/flutter/whats-new-in-flutter-3-27-28341129570c">Flutter 3.27 release blog</a> post for even more updates. See you next year!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=778dd7a80983" width="1" height="1" alt=""><hr><p><a href="https://medium.com/dartlang/announcing-dart-3-6-778dd7a80983">Announcing Dart 3.6</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 3.1 & a retrospective on functional style programming in Dart 3]]></title>
            <link>https://medium.com/dartlang/dart-3-1-a-retrospective-on-functional-style-programming-in-dart-3-a1f4b3a7cdda?source=rss-ae996dbdd76e------2</link>
            <guid isPermaLink="false">https://medium.com/p/a1f4b3a7cdda</guid>
            <category><![CDATA[dartlang]]></category>
            <category><![CDATA[announcements]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[releases]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Marya Belanger]]></dc:creator>
            <pubDate>Wed, 16 Aug 2023 18:00:20 GMT</pubDate>
            <atom:updated>2023-08-16T18:00:20.900Z</atom:updated>
            <content:encoded><![CDATA[<h4>Pattern matching and exhaustive switches come together to enable functional style data models that blend seamlessly with Dart’s object-oriented core.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IWd8aRO__OzDkJVsjfoe2A.png" /><figcaption>Diff of a Dart 3 refactor using functional style features within Dart’s internal code base</figcaption></figure><p><em>Today we’re releasing Dart 3.1, our first stable release since the major </em><a href="https://medium.com/dartlang/announcing-dart-3-53f065a10635"><em>Dart 3.0</em></a><em> release in May. Dart 3.1 contains a handful of minor updates and a few API adjustments to further use class modifiers introduced in 3.0 (which you can read more about in the </em><a href="https://github.com/dart-lang/sdk/blob/main/CHANGELOG.md#310"><em>changelog</em></a><em>). Mostly, though, we’ve been spending our time on new roadmap items that we hope to see reach beta and stable over the coming releases. Stay tuned for more about that in the future!</em></p><p><em>So, in place of a traditional release post, we’re revisiting a subset of Dart 3’s major features to talk about how they can completely change, and in some cases, greatly improve the way you write and structure your Dart code.</em></p><h3>How do you model data?</h3><p>Object-oriented (OO) and functional languages differ in many ways, but it’s arguable that <em>how each paradigm models data</em> is the defining characteristic that separates them. Specifically, the question of modeling different variations of related data and the operations on those variants.</p><p>But <em>“how should I model this data?”</em> is usually not something we consciously give much thought to when starting a new project. We tend to default to whatever data modeling paradigm is common to the type of language we’re using, as opposed to the inverse of choosing the language based on the model that makes the most sense for our data.</p><p>If you’re using an OO language, you’ll model data with class hierarchies and operations on subtypes. If you’re using certain functional languages, the equivalent to the class hierarchy model is the <a href="https://en.wikipedia.org/wiki/Algebraic_data_type">algebraic data type</a> model, whose equivalent to operating on subtypes is switching over them with <a href="https://en.wikipedia.org/wiki/Pattern_matching">pattern matching</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mA116alArq7XKrm_PSCjyw.png" /><figcaption>Simplified side-by-side comparison of the object-oriented class hierarchy model and the functional algebraic data type model</figcaption></figure><p>Dart is an object-oriented language, but has been steadily incorporating functional features over time, allowing for a more multi-paradigm approach to data modeling. Most recently, Dart 3 added <a href="https://dart.dev/language/patterns">pattern matching</a>, new functionality on <a href="https://dart.dev/language/patterns#switch-statements-and-expressions">switch</a>, and <a href="https://dart.dev/language/class-modifiers#sealed">sealed types</a>. These features make it possible to implement algebraic data types in Dart, allowing you to write functional style code while continuing to maximize the capabilities of Dart’s object-oriented core.</p><p>Multi-paradigm languages like Dart give you the tools and the opportunity to choose how you design anything from a single line expression, to entire class hierarchies. You can consider which model makes the most sense for your project, or even just for your personal preference. To help you make the best decision, this article summarizes the structure and strengths of each paradigm separately, and then teaches you how to use new features in Dart 3 to refactor some classic object-oriented designs that most benefit from being written in a functional style.</p><h4>Object-oriented approach</h4><p>When you have operations specific to different data types, the standard organization approach in OO languages is to create a method on a base class, and a set of subclasses that override the base class to define their unique behavior. Each subclass has its data and operations together in one place inside its declaration.</p><p>Take this (high-level pseudocode) example of modeling recipes. It makes sense to have recipe objects, coupling ingredients and steps together with the recipe. The recipe base class would probably have some functions for the cooking methods that each recipe overrides with their unique requirements:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a6f22bcd1ef1ff84f0fe4b47689a631/href">https://medium.com/media/3a6f22bcd1ef1ff84f0fe4b47689a631/href</a></iframe><p>Class hierarchies with instance methods make it easy to add new subclasses without having to touch any existing code. This works perfectly for some domains, like Flutter, where you have countless widgets that all extend the Widget class. Each widget can uniquely extend and override any necessary behavior directly inside their definition. You <em>definitely</em> don’t need to know how every widget subtype defines its methods to add specialized behavior to your own widgets.</p><h4>Functional approach (algebraic data types)</h4><p>You can think of functional style architecture as the inverse of OO architecture. Instead of having all the code for <em>one type in one place</em> (OO instance methods in subclass declarations), you have all the code for <em>one operation in one place</em> (functional switching over types to define behavior).</p><p>Which begs the question, when <em>does</em> it make sense to know how every subtype in a hierarchy defines an operation? It could be for a few reasons:</p><ul><li>When adding, maintaining, and understanding variants of the same operation’s behavior across types is easier to do when they’re all side by side in the code.</li><li>When you can’t modify the subclasses yourself, but you want to define new behavior that is specific to each of them.</li><li>When the variations of an operation’s behavior for different types are more related to each other than they are to the types that they’re operating on<em>.</em></li></ul><p>Sometimes it’s obvious, but mostly it’s just a perspective shift. Think about the recipe example again. From the point of view of, say, an oven manual, it would make a lot more sense to group bake instructions together in one place for each recipe:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fce49155327bfd44fd1f78a4ca589728/href">https://medium.com/media/fce49155327bfd44fd1f78a4ca589728/href</a></iframe><p>In this example, the program structure is focused on the bake operation. Whatever types bake operates on are simply different possible outputs of the same function; bake is independent of the types it operates on.</p><p>This is the <strong>algebraic data type model </strong>(named “algebraic” after mathematical set theory). It’s the core organizational model of functional languages, in the same way class hierarchies are core to OO languages. Algebraic data types separate behavior from data by grouping behavior for all types together by operation.</p><p>And now, it’s possible to cohesively implement algebraic data types with Dart 3!</p><h3>Modeling object oriented algebraic data types</h3><p>Functional languages generally implement <a href="https://en.wikipedia.org/wiki/Algebraic_data_type">algebraic data types</a> by pattern matching over the cases in a <a href="https://en.wikipedia.org/wiki/Tagged_union">sum type</a> to assign behavior to each variant. Dart 3 achieves the same with <a href="https://dart.dev/language/patterns#switch-statements-and-expressions">pattern matching</a> in switch cases, and takes advantage of the fact that OO subtyping already naturally models sum types. This allows us to implement truly <a href="https://dart.dev/language/patterns#algebraic-data-types">multi-paradigm algebraic data types</a> using objects that blend into Dart seamlessly.</p><p>The following sections show you how to design algebraic data type models in Dart, alongside pre-Dart 3 examples of the same functionality.</p><ul><li>First, we’ll explain how to group type-based variants of an operation together by switching over <a href="https://dart.dev/language/pattern-types#object">object patterns</a>.</li><li>Then, we’ll take a step back and look at how to architect the subclasses themselves with the new <a href="https://dart.dev/language/class-modifiers#sealed">sealed</a> class modifier, to ensure the switch defines behavior for <a href="https://dart.dev/language/branches#exhaustiveness-checking">all possible subtypes the object might take</a>.</li></ul><h4>Grouping behaviors across types</h4><p>Individual parts of the Dart language (like statements, classes, and literals) each have their own definitions in class hierarchies, but are all subject to operations from multiple systems (such as parser, formatter, and compiler operations). Imagine how confusing the language implementation would be if every function that applied to every language element had to be defined inside those elements’ declarations! It would look something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ffb98bc8686a75e1c08e1459a68267a0/href">https://medium.com/media/ffb98bc8686a75e1c08e1459a68267a0/href</a></iframe><p>Dart’s internal code already naturally leans towards the functional approach of separating functions from type definitions for this reason. Take the <a href="https://github.com/dart-lang/sdk/blob/main/pkg/analyzer/lib/src/error/annotation_verifier.dart">annotation_verifier</a> library in Dart’s analyzer. It contains functions that define behavior for annotations (like @override or @deprecated) depending on the part of code the annotation is attached to (like how @override affects a class as opposed to a field).</p><p>But assigning behavior per type is not as straightforward as making the decision to separate the behavior out in the first place. The standard way to define behaviors by type uses chained if-else statements, which you see a lot in the annotation verifier. Take the following verification function written without using any Dart 3 features. It verifies the behavior of the <a href="https://github.com/dart-lang/sdk/commit/4079a47cc4fb8f88e2dd9b7faff3bd587931a379">recently contributed</a> @visibleOutsideTemplate annotation that opts out of the cascading effects of another annotation, @visibleForTemplate:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a3c434f36ddd91f30755438674324b2b/href">https://medium.com/media/a3c434f36ddd91f30755438674324b2b/href</a></iframe><p>The function uses elaborate chained if-else statements, testing whether the grandparent of the annotation is a certain kind of declaration (either ClassDeclaration, EnumDeclaration, or MixinDeclaration), and then defining its behavior based on the type.</p><p>With Dart 3, you can use object patterns in switch cases to significantly refactor this structure to a more declarative style, making it shorter and easier to read. And the original author <a href="https://github.com/dart-lang/sdk/blob/4079a47cc4fb8f88e2dd9b7faff3bd587931a379/pkg/analyzer/lib/src/error/annotation_verifier.dart#L417-L426">did just that</a>! 16 lines of chained if-else statements are pared down to a 7-line switch statement:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/80466ddfaaece549a847e51911950a0b/href">https://medium.com/media/80466ddfaaece549a847e51911950a0b/href</a></iframe><p>Each case here is an <a href="https://dart.dev/language/pattern-types#object">object pattern</a> that matches against the static type of grandparent. Instead of saying if (object is Type &amp;&amp; object.property != null), each case checks if the object’s pattern matches the pattern Type(propertyOfType). Plus, when an object matches an object pattern, it implicitly requires that it’s not null, so there’s no need for an explicit null check!</p><p>Object patterns can also contain nested <a href="https://dart.dev/language/pattern-types#variable">variable patterns</a> that allow you to extract (or <a href="https://dart.dev/language/patterns#destructuring"><em>destructure</em></a>) property values from an object in the same line of code you’re matching against. The syntax (:var metadata) just means “match and declare a new variable with the same name as this getter”. This is how the variable metadata comes into scope for the final for loop. Pretty concise!</p><p>Notice that the for loop is now common between each case. Each type’s declaredElement property is actually a different subtype of another type, InterfaceElement (either a classElement, enumElement, or mixinElement). So, the pre-Dart 3 chained if-else statement iterated over metadata in each if clause separately, to ensure final annotation would be type safe for each of the possible types that metadata could take.</p><p>Now, the refactored structure uses deeply nested object patterns for each case, to upcast metadata to its supertype, InterfaceElement. This makes a single shared for loop iterating over metadata type safe across the cases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*qYQb8DZyeJDFD-VKEb4P6Q.png" /><figcaption>Annotated depiction of the syntax for a deeply nested object and variable patterns</figcaption></figure><p>Switching over object patterns matters to Dart’s algebraic data type implementation because of its ability to concisely test subtypes and destructure values. A nice side effect is the simultaneous assurances that can be provided by a single line of code. To reiterate, each case pattern in this refactor is simultaneously verifying:</p><ul><li>The object is one of the types ClassDeclaration, EnumDeclaration, or MixinDeclaration.</li><li>The object has the property declaredElement.</li><li>declaredElement has the property metadata.</li><li>metadata is of type InterfaceElement.</li><li>None of the objects or properties in question are null.</li></ul><p>This is the perfect example of how thoroughly Dart 3 implements patterns to account for so many nuances of OO languages, and really make object-oriented algebraic data types a realistic design option in Dart.</p><p>Type tests over object patterns are great for separating behavior from types. But its missing one feature of OO subtyping, where the compiler lets you know if you declare a new subtype but don’t define behavior for one of its supertype’s abstract methods. How can Dart’s algebraic data type model implement the same safety assurances when we’re no longer dealing with instance methods on type declarations? The answer is <em>exhaustiveness checking</em>.</p><h4>Exhaustiveness checking</h4><p>Functional languages’ implementations of algebraic data types use enumerable sum types, which means the compiler is always aware of all the possible variations of the type being switched over. The compiler can then let you know if your switch is missing a case, and therefore that it’s possible some values might fall through that switch without being addressed.</p><p>This is called <a href="https://dart.dev/language/branches#exhaustiveness-checking">exhaustiveness checking</a>. It has technically always existed in Dart for enumerable types like enums and booleans. Those types have a set of possible values that cannot change, and if you’re switching over them, the compiler knows when you’ve missed one and warns you. Using a default clause is another kind of pseudo exhaustiveness. Since default matches all cases not explicitly accounted for, it causes the compiler to consider a switch exhaustive without knowing if all potential types are actually accounted for.</p><p>As mentioned, we wanted to use subtypes instead of sum types for Dart’s version of algebraic data type modeling. But since classes in Dart can be extended from any library, it would be impossible for the compiler to exhaustively enumerate subtypes of a class since it can’t know if any subclasses are declared in external libraries.</p><p>To get around this and complete Dart’s algebraic data type implementation, we added the <a href="https://dart.dev/language/class-modifiers#sealed">sealed class modifier</a> to Dart 3. A sealed class cannot be extended or implemented from any library but its own (<a href="https://dart.dev/language/libraries">the file that contains its definition</a>). This ensures the compiler is always aware of any and all possible subtypes, making them fully enumerable.</p><p>Here’s an example of an actual refactor that went into the Dart SDK as part of the 3.1 release: <a href="https://github.com/dart-lang/sdk/commit/c3e815bc7ad488eddf00344ab4106485a9d1ba32#diff-e98c6de423bf7e0b5b961cd10efed50330004229243aa87c18ad6314fef054b0L879-R879">sealing </a><a href="https://github.com/dart-lang/sdk/commit/c3e815bc7ad488eddf00344ab4106485a9d1ba32#diff-e98c6de423bf7e0b5b961cd10efed50330004229243aa87c18ad6314fef054b0L879-R879">FileSystemEvent</a> so its subtypes can be exhaustively switched over. Brace yourself, refactors are hard…</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ebbec98bf5109bbc14be7867a3b4c117/href">https://medium.com/media/ebbec98bf5109bbc14be7867a3b4c117/href</a></iframe><p>Just kidding, that wasn’t hard at all! It should be noted, though, that sealing an existing class hierarchy is a breaking change. Code targeting older versions of Dart won’t be able to implement or extend the class, so always check dependencies and alert any users that might be subtyping your classes elsewhere.</p><p>Sealing FileSystemEvent allows the events produced by FileSystemEntity.watch, which correspond to the subtypes of FileSystemEvent, to be exhaustively switched over. It’s typical to listen to this stream of events and use <a href="https://github.com/dart-lang/sdk/issues/52273">chained </a><a href="https://github.com/dart-lang/sdk/issues/52273">if-else</a> statements to determine an action based on the type of the events that occur.</p><p>But sealing the base class doesn’t only allow you to switch over object patterns, like the _checkVisibleOutsideTemplate example in the previous section. It also ensures that while doing so, you’re accounting for every possible value that could arise for that type, without the need for a default case:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9618c7e18185c98dcb4e4cf9968759f9/href">https://medium.com/media/9618c7e18185c98dcb4e4cf9968759f9/href</a></iframe><p>If a new subtype was ever added that extends FileSystemEvent, perhaps FileSystemSyncEvent for example, the compiler would be aware of it because it could only be added to the <a href="https://github.com/dart-lang/sdk/blob/main/sdk/lib/io/file_system_entity.dart">same library</a> as FileSystemEvent. Since the class hierarchy is sealed, the compiler requires any switch over its instances to be exhaustive, and will generate <a href="https://dart.dev/tools/diagnostic-messages#non_exhaustive_switch_expression">an error</a> to alert the user (who wrote the switch, not the library owner) of unhandled cases:</p><pre>The type &#39;FileSystemEvent&#39; is not exhaustively matched by the switch cases since it doesn&#39;t match &#39;FileSystemSyncEvent&#39;</pre><p>Combining sealed classes and switches over object patterns enables a complete, object-oriented algebraic data type style of program architecture in Dart.</p><h4>Bonus functional features</h4><p>The exhaustive switch example above includes even more functional features from Dart 3 than just the ones that facilitate algebraic data types.</p><p>Notice that the switch is to the right of the _fileListener function’s return statement—that’s Dart 3’s new <a href="https://dart.dev/language/branches#switch-expressions">switch expression</a>. General emphasis on expressions and functions is a key element of functional languages. Dart 3 made switch expressions that can produce a value and go anywhere an expression is allowed.</p><p>And what is _fileListener returning in the previous example, anyway? That’s a <a href="https://dart.dev/language/records">record</a>, another new Dart 3 feature also related to functional programming. Records let you return multiple heterogeneous values from a function, extending the usefulness of functions in Dart, and moving further away from reliance on custom classes (which would be the only other way to return multiple values of different types without losing their types in the process).</p><h3>Summary</h3><p>You can model algebraic data types in Dart by:</p><ul><li>Writing a function that switches <em>on</em> an instance of a sealed class, and <em>over</em> its subtypes,</li><li>And defining variances in the behavior of each subtype in the switch cases.</li></ul><p>Switching over object patterns allows you to keep all the operations together in a succinct way, and exhaustiveness checking ensures the compiler will alert you if you’re missing behavior definitions for any types. And it’s all built on top of the object-oriented classes Dart already uses.</p><p>The best part is, you don’t have to pick either an object-oriented or functional style; the two paradigms blend together and you can use whichever style best fits the operation you’re defining.</p><p>You can make existing class hierarchies more functional with minor modifications, and even mix the use of instance methods with algebraic data types within the same class hierarchy. Whether it makes sense to couple behavior closely to a type, or group behavior for different types in one function, you can use the style that makes the most sense.</p><p>We hope this introduction piques your interest in functional programming and trying out the new Dart 3 features. Who knows, maybe we’ll see the first fully-functional-style Dart program from one of you soon!</p><h4>Resources</h4><p><em>To learn more about functional programming in and around Dart, check out these resources:</em></p><ul><li>The official Dart documentation on <a href="https://dart.dev/language/patterns">patterns</a> and <a href="https://dart.dev/language/branches#exhaustiveness-checking">exhaustiveness checking</a>.</li><li>The <a href="https://codelabs.developers.google.com/codelabs/dart-patterns-records#0">patterns and records codelab</a> about refactoring Flutter code with Dart 3.</li><li>This <a href="https://www.droidcon.com/2023/08/07/the-joy-of-functional-programming-in-dart/">community talk</a> from FlutterCon about functional programming in Dart.</li><li>This <a href="https://journal.stuffwithstuff.com/2023/08/04/representing-heterogeneous-data/">blog post</a> about modeling heterogeneous data from the personal blog of Bob Nystrom (who wrote <a href="https://github.com/dart-lang/language/blob/main/accepted/3.0/patterns/feature-specification.md">the design for patterns in Dart</a>!).</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a1f4b3a7cdda" width="1" height="1" alt=""><hr><p><a href="https://medium.com/dartlang/dart-3-1-a-retrospective-on-functional-style-programming-in-dart-3-a1f4b3a7cdda">Dart 3.1 &amp; a retrospective on functional style programming in Dart 3</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[Better isolate management with Isolate.run()]]></title>
            <link>https://medium.com/dartlang/better-isolate-management-with-isolate-run-547ef3d6459b?source=rss-ae996dbdd76e------2</link>
            <guid isPermaLink="false">https://medium.com/p/547ef3d6459b</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[dartlang]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[asynchronous-programming]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Marya Belanger]]></dc:creator>
            <pubDate>Tue, 24 Jan 2023 19:46:18 GMT</pubDate>
            <atom:updated>2023-01-26T01:21:02.743Z</atom:updated>
            <content:encoded><![CDATA[<h4>Dart 2.19 introduces a new function that makes implementing concurrency as simple as a single line of code.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/0*Bt-V4nlGjNKquFhK" /><figcaption>A benchmark test showcasing the speed of the new Isolate.run() function</figcaption></figure><p>All Dart code runs in isolates. Whether you implement multiple isolates to enable <a href="https://dart.dev/guides/language/concurrency">concurrency</a> in your Dart programs is up to you. <em>How</em> you can implement multiple isolates is up to us on the Dart team, and in Dart 2.19, we’ve made a huge upgrade to the process that we’re excited to share. Meet Isolate.run()!</p><p>run() takes all of the complexity of setting up and managing isolates and completely abstracts it into a single function call. It’s been possible to use isolates with a handful of primitives for a while now. But, even with all <a href="https://medium.com/dartlang/dart-2-15-7e7a598e508a#:~:text=publishers%2C%20and%20more.-,Fast%20concurrency%20with%20worker%20isolates,-Just%20about%20all">the recent performance improvements</a> for isolates, the process was at best, tedious, and at worst, error-prone.</p><p>To appreciate how much of an improvement run() is, this article breaks down the previous method of building out the functionality piece-by-piece from low-level primitives. Then, we’ll contrast that to using Isolate.run(), and show you how it works on the inside. Even if you’ve never used isolates before, we’re sure that run() will get you excited to try them out!</p><h4>Isolates</h4><p>Isolates are a fairly straightforward concept. An <a href="https://medium.com/dartlang/dart-asynchronous-programming-isolates-and-event-loops-bffc3e296a6a">isolate</a> is essentially a single thread of execution in Dart. They let you execute parts of your code in parallel. You can start new parallel executions (as many as you want) and tell them what to do, right from main (the main thread, or <a href="https://dart.dev/guides/language/concurrency#the-main-isolate">main isolate</a>). Isolates don’t share memory; instead, they pass messages back and forth to communicate. So, you don’t have to worry about typical multithreading problems, like race conditions, or mutexes and locks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/0*eCogwJXZtpbg5Hbq.png" /></figure><p>Sounds great! But how do you use them? Before Isolate.run(), that’s where things became tricky.</p><p><a href="https://api.dart.dev/stable/dart-isolate/Isolate-class.html">The isolate API</a> is made up of low-level primitives that provide a wide range of functionality. Granularity like that is great when you need to customize your isolates’ functionality. Granularity is not so great, though, when it’s necessary to use isolates <em>at all</em>. Especially since almost all of the use cases for isolates require the same basic configurations for setup and management. This basically meant exposing every implementation detail for you, Dart’s users, to handle yourselves.</p><p>Let’s take a look at a typical isolate setup to better understand the tedious process that Isolate.run() solves.</p><h4>Using Isolates (before)</h4><p>You can think of <a href="https://api.dart.dev/stable/dart-isolate/Isolate/spawn.html">Isolate.spawn()</a> as the old starting point for isolates. Flutter’s compute function was built off of spawn(). It takes a method to invoke as its entrypoint argument, plus any arguments for that method, and other configurations for the isolate itself. In the past, this entrypoint could only be a top-level or static method.</p><p>Isolate.spawn(_readAndParseJson, filename);</p><p>Isolate created, all done! Just kidding. Not even close.</p><p>Calling spawn won’t return anything to actually work with. It only returns an isolate object, which simply confirms the isolate has started.</p><p>The main isolate and the spawned isolate (the isolate created by spawn()) can’t communicate directly, beyond the initial arguments passed on creation. Realistically, even if you don’t need any computation results back from the spawned isolate, you would still want some kind of verification that the computation succeeded, so you’re always going to want a message back.</p><p>To enable communication, you have to set up ports. You create a ReceivePort object before calling spawn. The sendPort member of the ReceivePort object goes to the spawned isolate as another argument for spawn.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a4077fd46ce2a68512e9f71114184b0d/href">https://medium.com/media/a4077fd46ce2a68512e9f71114184b0d/href</a></iframe><p>This means the function you pass to spawn has to be <em>specifically</em> configured to do something with that sendPort. In other words, you can’t just reuse existing functions with isolates. So instead of passing spawn a regular function that just reads and parses a JSON file, you would create something like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c3916b9af5918d16e89f9437412f5be/href">https://medium.com/media/3c3916b9af5918d16e89f9437412f5be/href</a></iframe><p>Your special, isolate-friendly, JSON-decoding function can simply “return result” and you’re all done, right? Not quite. The result needs to be sent through responsePort. That’s how isolates communicate with ports. You can use another primitive, <a href="https://api.dart.dev/stable/dart-isolate/Isolate/exit.html">Isolate.exit()</a> to return the result efficiently and close the spawned isolate at the same time:</p><p>Isolate.exit(responsePort, result);</p><p>The exit() function <em>transfers</em> the memory that holds the message in the spawned isolate to the main isolate (as opposed to copying it over) and safely closes the isolate.</p><p>Let’s string this all together. Since result in this example is parsed JSON , you’d probably want to destructure it a little to actually use it. For the sake of clean code, instead of planting those three lines that create the receivePort and the isolate, and await their response, right into main(), we should put them in their own function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6f6acb3dc6833cf9b34ee4a65fd474b9/href">https://medium.com/media/6f6acb3dc6833cf9b34ee4a65fd474b9/href</a></iframe><p>What’s being accomplished is relatively straightforward. It’s the exposure of implementation details that makes it <em>feel</em> complicated, like ports for message passing, and needing a dedicated function for dealing with ports that’s otherwise isolate-agnostic.</p><h4>Error handling</h4><p>The example so far <em>still</em> isn’t really a “complete”, production-ready implementation. You’d be doing yourself a disservice to leave out any kind of error handling, but it’s commonly forgotten as an additional step in an already substantial process. Without any error handling, if an uncaught async error were to crash your isolate, for example, you wouldn’t know what happened to cause the error, or even be alerted that <em>anything had happened at all</em>.</p><p>Covering every error handling possibility for isolates would be extensive, but in general it would involve a few more additions to the code.</p><p>You could, as a minimum, add the errorsAreFatal, onExit, and onError parameters to the spawn call:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b60a3ddf74c038ebee17f3be498ea7d0/href">https://medium.com/media/b60a3ddf74c038ebee17f3be498ea7d0/href</a></iframe><p>This ensures that resultPort receives a message even if the spawned isolate terminates without sending a result, or if it has any uncaught errors. Making errors fatal means uncaught errors exit the isolate as a safety precaution, to ensure it terminates at all.</p><p>The onExit argument makes the isolate send null to the port upon exiting. The onError argument makes an uncaught error send a list of two strings to the port (the toString of both the error and stack trace).</p><p>Reusing the result port lets you avoid creating more ports, so you only have to look for messages in one place. But it also means you need to distinguish the onExit and onError messages from the result value. Here, we assume that the JSON must be a Map, so it cannot be a list or null. Otherwise you’d also have to wrap the result in something recognizable. You would have to create a (trivial) message protocol on top of the port messages.</p><p>Beyond that minimum, you could then check response for specific errors. One such case would be checking if resultPort is null, meaning the isolate terminated without sending results:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f9685110e29257f5f98445596375d34/href">https://medium.com/media/1f9685110e29257f5f98445596375d34/href</a></iframe><p>Another would be checking if the result is a list, meaning an uncaught error occurred:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/72f7164fb07f16c509283dadd6b23501/href">https://medium.com/media/72f7164fb07f16c509283dadd6b23501/href</a></iframe><p>Then, finally, handle an actual result:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/01681a8643cf50c9bc1c0956bf05ac27/href">https://medium.com/media/01681a8643cf50c9bc1c0956bf05ac27/href</a></iframe><p>In any case, you’d want to put spawn in a try block to check if sending the entrypoint to the new isolate failed. If it did, the result port won’t get any message, and needs to be closed:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3e3b35ae765e1ef261a74858b73e2d49/href">https://medium.com/media/3e3b35ae765e1ef261a74858b73e2d49/href</a></iframe><p>Providing a bare minimum of error handling ensures that the result port is always closed, and _spawnAndReceieve always completes, no matter how the spawned isolate exits. You could also make things <em>nicer</em>, for example, by catching and sending errors and stack traces back as actual objects, not just strings like the onError handler.</p><p>Error handling obviously introduces a lot of variation, and with it the mental overhead of deciding how to approach it and what to factor for. It’s understandable that it’s commonly left out of primitive isolate setup.</p><h4>Using Isolates (after)</h4><p>Isolate.run() sets up all parts of isolate implementation with the primitives you previously had to use yourself, in a single function call:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/27ee342686cba4d9546ef2a49a0dbfd9/href">https://medium.com/media/27ee342686cba4d9546ef2a49a0dbfd9/href</a></iframe><p>No ports, no separate spawning, exiting, or error handling, and no special return structure. Perhaps the best part, the entrypoint you pass to run can be any existing function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/20a0d24ac90487ddb8d0cc1cf66a71be/href">https://medium.com/media/20a0d24ac90487ddb8d0cc1cf66a71be/href</a></iframe><p>This example shows an <em>asynchronous</em> function, but run could just as easily execute a <em>synchronous</em> function. The run function itself always returns asynchronously, which is all that matters.</p><p>The entrypoint can also be a <em>function expression</em>, written directly inline wherever you call run. Isolates, and any higher-level APIs written on top, are no longer limited to running only static or top-level functions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c270b53649cac8d66aaea6af997502dd/href">https://medium.com/media/c270b53649cac8d66aaea6af997502dd/href</a></iframe><p>The additional message parameter is no longer necessary, and you can avoid packing and unpacking arguments in data structures like lists.</p><p>You don’t have to think much about error handling at all. The run function combines local and remote error capturing, handling and cross-isolate communication, and exposes the result as a single normal (asynchronous) error that you can catch in a standard try/catch. You can forget isolates, and treat it as a normal function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e9bf5b788a505cbf800d506948ba838d/href">https://medium.com/media/e9bf5b788a505cbf800d506948ba838d/href</a></iframe><p>Isolate.run() enables much cleaner and ergonomic code. Flutter’s compute function even switched over to using run instead of spawn!</p><h4>Inside Isolate.run()</h4><p>Take a look at the <a href="https://api.dart.dev/dev/3.0.0-125.0.dev/dart-isolate/Isolate/run.html#implementation:~:text=isolate%20for%20debugging.-,Implementation,-%40Since(%222.19">implementation of </a><a href="https://api.dart.dev/dev/3.0.0-125.0.dev/dart-isolate/Isolate/run.html#implementation:~:text=isolate%20for%20debugging.-,Implementation,-%40Since(%222.19">run</a> itself. It digs into all the low-level isolate-related APIs (which would’ve been your job to implement before) to construct a “perfect”, comprehensive isolate setup. It takes the method to execute, computation, and sets up all the ports and their returns to account for efficient message passing between isolates.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ca8d776662ead618f17933fb574dc36/href">https://medium.com/media/4ca8d776662ead618f17933fb574dc36/href</a></iframe><p>There’s <em>thorough</em> error handling for every potential case. The run function checks whether an isolate dies before it’s done computing. If the computation throws, the isolate terminates and throws the same error to the main isolate.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f15aa7cd2ffcaec4c1c64f9f57f22be/href">https://medium.com/media/2f15aa7cd2ffcaec4c1c64f9f57f22be/href</a></iframe><p>If an uncaught asynchronous error occurs, the isolate terminates and reports the error asynchronously to the main isolate. If the main isolate terminates first, the spawned isolate terminates and treats the situation as an uncaught async error.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/87593ee587c105fb32549fe1368bb783/href">https://medium.com/media/87593ee587c105fb32549fe1368bb783/href</a></iframe><p>Lastly, run always uses exit to safely shut down. That means data is efficiently transferred from isolate to isolate without actually copying it.</p><h4>Summary</h4><p>The run function is ideal for starting one computation and waiting for the results. The primitives are still there if you want to build out your own isolate setup for something that run doesn’t cover, like a <a href="https://github.com/dart-lang/samples/blob/master/isolates/bin/long_running_isolate.dart">long-running isolate</a> that can send and receive messages multiple times. For most cases though, replacing spawn and all its supporting configurations with a single run statement should be used over any other configuration.</p><p>If you’d never tried isolate management before run, it would be hard to believe all this functionality previously had to be implemented by the user! Isolate.run() — available in Dart 2.19 and Flutter 3.7 — makes code so much more ergonomic, and makes isolates so much easier to use. What will you do with all the time run saves you?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=547ef3d6459b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/dartlang/better-isolate-management-with-isolate-run-547ef3d6459b">Better isolate management with Isolate.run()</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>