<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="4.4.1">Jekyll</generator><link href="https://handform.net/feed.xml" rel="self" type="application/atom+xml" /><link href="https://handform.net/" rel="alternate" type="text/html" /><updated>2026-12-03T10:41:43+00:00</updated><id>https://handform.net/feed.xml</id><title type="html">handform</title><subtitle>Small things to get your hands on, by Craig McMahon.</subtitle><author><name>Craig McMahon</name></author><entry><title type="html">More powerful enums in Dart</title><link href="https://handform.net/2020/05/30/more-powerful-enums-in-dart.html" rel="alternate" type="text/html" title="More powerful enums in Dart" /><published>2020-05-30T00:00:00+00:00</published><updated>2020-05-30T00:00:00+00:00</updated><id>https://handform.net/2020/05/30/more-powerful-enums-in-dart</id><content type="html" xml:base="https://handform.net/2020/05/30/more-powerful-enums-in-dart.html"><![CDATA[<p>Coming from the Swift world, I’d missed powerful <code class="language-plaintext highlighter-rouge">enum</code> types in Flutter development. But there’s a <strong>pub.dev</strong> package for that, and in this article we’ll explore how to use it to clean up your Redux actions.</p>

<h3 id="why-enums">Why enums?</h3>

<p>An enum(erated) type is a great way to express a collection of associated values in a way where the language you’re using will help you write branching code that considers all possible cases. This immediately stands out as something we might want to do with our Redux actions:</p>

<div class="language-dart highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">enum</span> <span class="n">GameAction</span> <span class="p">{</span>
    <span class="n">start</span><span class="p">,</span>
    <span class="c1">// ...a bunch of other actions...</span>
    <span class="n">finish</span>
<span class="p">}</span>
</code></pre></div></div>

<p>The advantage of this is that we can <code class="language-plaintext highlighter-rouge">switch</code> over a <code class="language-plaintext highlighter-rouge">GameAction</code> to <strong>make sure</strong> that our reducer handles all possible actions, and the compiler will complain if we don’t:</p>

<div class="language-dart highlighter-rouge"><div class="highlight"><pre class="highlight"><code>    <span class="c1">// Warning: missing case clause for 'finish'</span>
    <span class="k">switch</span> <span class="p">(</span><span class="n">action</span><span class="p">)</span> <span class="p">{</span>
    <span class="k">case</span> <span class="n">GameAction</span><span class="o">.</span><span class="na">start</span><span class="o">:</span>
    <span class="k">return</span> <span class="n">state</span><span class="o">.</span><span class="na">copyWith</span><span class="p">(</span><span class="nl">inProgress:</span> <span class="kc">true</span><span class="p">)</span>
    <span class="p">}</span>
</code></pre></div></div>

<blockquote>
  <p>It’s nice when the compiler can help you to manage your state!</p>
</blockquote>

<p>But there’s a problem. We need to be able to pass parameters along with our actions. For example, for the <code class="language-plaintext highlighter-rouge">finish</code> action we want to send a <code class="language-plaintext highlighter-rouge">finalScore</code> parameter.</p>

<h3 id="associated-values">Associated values</h3>

<p>In Swift, enums are a lot more useful, because cases can have “associated values”:</p>

<div class="language-swift highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">enum</span> <span class="kt">GameAction</span> <span class="p">{</span>
    <span class="k">case</span> <span class="n">start</span>
    <span class="k">case</span> <span class="nf">finish</span><span class="p">(</span><span class="nv">finalScore</span><span class="p">:</span> <span class="kt">Int</span><span class="p">)</span>
<span class="p">}</span>
</code></pre></div></div>

<p>We’re still able to use <code class="language-plaintext highlighter-rouge">switch</code>, only this time we can extract the values we need:</p>

<div class="language-swift highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">switch</span> <span class="n">action</span> <span class="p">{</span>
<span class="k">case</span> <span class="o">.</span><span class="nv">start</span><span class="p">:</span>
    <span class="c1">// ...</span>
<span class="k">case</span> <span class="o">.</span><span class="nf">finish</span><span class="p">(</span><span class="k">let</span> <span class="nv">finalScore</span><span class="p">):</span>
    <span class="c1">// apply finalScore to state</span>
<span class="p">}</span>
</code></pre></div></div>

<p>It would be great to have a way to do this in Dart. Luckily, there is one!</p>

<h3 id="super-enum">Super Enum</h3>

<p>The Super Enum package hosted <a href="https://pub.dev/packages/super_enum">here at pub.dev</a> provides just the functionality we need. It allows us to create a supercharged enumerated type with associated values.</p>

<p>It works using code generation. Like me, perhaps you’re not comfortable with the idea of generating large bits of your codebase, but there are plenty of useful packages that work this way (especially for serialisation), so it should be a tool at your disposal.</p>

<p>After following the <a href="https://pub.dev/packages/super_enum">installation instructions</a>, we’re ready to begin. Don’t forget to install the generator by adding <code class="language-plaintext highlighter-rouge">super_enum_generator</code> to your <code class="language-plaintext highlighter-rouge">dev_dependencies</code> in <code class="language-plaintext highlighter-rouge">pubspec.yaml</code>, and <code class="language-plaintext highlighter-rouge">build_runner</code> if it’s not there already.</p>

<h3 id="declaring-our-intention">Declaring our intention</h3>

<p>As with many other packages that rely on <a href="https://dart.dev/tools/build_runner"><code class="language-plaintext highlighter-rouge">build_runner</code></a>, we start by defining a private type that tells the generator what we expect to see in the generated type:</p>

<div class="language-dart highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">import</span> <span class="s">'package:super_enum/super_enum.dart'</span><span class="o">;</span>
<span class="kn">part</span> <span class="s">"game_action.g.dart"</span><span class="o">;</span>

<span class="nd">@superEnum</span>
<span class="kt">enum</span> <span class="n">_GameAction</span> <span class="p">{</span>
  <span class="nd">@object</span>
  <span class="n">StartGame</span><span class="p">,</span>

  <span class="nd">@Data</span><span class="p">(</span><span class="nl">fields:</span> <span class="p">[</span>
    <span class="n">DataField</span><span class="p">&lt;</span><span class="kt">int</span><span class="p">&gt;(</span><span class="s">'finalScore'</span><span class="p">),</span>
  <span class="p">])</span>
  <span class="n">FinishGame</span>
<span class="p">}</span>
</code></pre></div></div>

<p>A few things to note:</p>

<ul>
  <li>we’ve declared a private <code class="language-plaintext highlighter-rouge">enum</code> <code class="language-plaintext highlighter-rouge">_GameAction</code> (private because of that underscore);</li>
  <li>we’ve decorated “regular” enumeration cases with <code class="language-plaintext highlighter-rouge">@object</code>;</li>
  <li>we’re using case names like <code class="language-plaintext highlighter-rouge">StartGame</code> instead of just <code class="language-plaintext highlighter-rouge">start</code>—I’ll explain why in the next section;</li>
  <li>we’ve decorated cases that have associated values with <code class="language-plaintext highlighter-rouge">@Data(fields: ...)</code> and then some <code class="language-plaintext highlighter-rouge">DataField</code> instances that declare the name and type of associated value.</li>
</ul>

<p>Now we run:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>flutter pub run build_runner build
</code></pre></div></div>

<h3 id="inspecting-the-generated-code">Inspecting the generated code</h3>

<p>Let’s peek inside the generated file <code class="language-plaintext highlighter-rouge">game_action.g.dart</code>, and see what’s there:</p>

<div class="language-dart highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// GENERATED CODE - DO NOT MODIFY BY HAND</span>

<span class="kn">part of</span> <span class="s">'game_action.dart'</span><span class="o">;</span>

</code></pre></div></div>

<p>Fair enough. Don’t touch!</p>

<div class="language-dart highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nd">@immutable</span>
<span class="kd">abstract</span> <span class="kd">class</span> <span class="nc">GameAction</span> <span class="kd">extends</span> <span class="n">Equatable</span> <span class="p">{</span>
  <span class="kd">const</span> <span class="n">GameAction</span><span class="p">(</span><span class="k">this</span><span class="o">.</span><span class="na">_type</span><span class="p">);</span>

  <span class="kd">factory</span> <span class="n">GameAction</span><span class="o">.</span><span class="na">startGame</span><span class="p">()</span> <span class="o">=</span> <span class="n">StartGame</span><span class="p">;</span>

  <span class="kd">factory</span> <span class="n">GameAction</span><span class="o">.</span><span class="na">finishGame</span><span class="p">({</span><span class="nd">@required</span> <span class="kt">int</span> <span class="n">finalScore</span><span class="p">})</span> <span class="o">=</span> <span class="n">FinishGame</span><span class="p">;</span>

</code></pre></div></div>

<p>You can see that for each case we specified a class has been generated that subclasses <code class="language-plaintext highlighter-rouge">GameAction</code> (note: no underscore). The classes themselves are declared at the end of the file, but here you can see factory constructors that produce them. And now you also see why we’ve used i.e. <code class="language-plaintext highlighter-rouge">StartGame</code> as a case name, since littering our namespace with type names like <code class="language-plaintext highlighter-rouge">Start</code> and <code class="language-plaintext highlighter-rouge">Finish</code> is not going to end well. You might consider making your case names even more explicit, like <code class="language-plaintext highlighter-rouge">StartGameAction</code>.</p>

<p>Moving on, we see the switch functionality that we need. If you’ve used Kotlin, it will look familiar:</p>

<div class="language-dart highlighter-rouge"><div class="highlight"><pre class="highlight"><code>  <span class="p">...</span>

  <span class="n">R</span> <span class="k">when</span><span class="p">&lt;</span><span class="n">R</span><span class="p">&gt;(</span>
      <span class="p">{</span><span class="nd">@required</span> <span class="n">FutureOr</span><span class="p">&lt;</span><span class="n">R</span><span class="p">&gt;</span> <span class="kt">Function</span><span class="p">(</span><span class="n">StartGame</span><span class="p">)</span> <span class="n">startGame</span><span class="p">,</span>
      <span class="nd">@required</span> <span class="n">FutureOr</span><span class="p">&lt;</span><span class="n">R</span><span class="p">&gt;</span> <span class="kt">Function</span><span class="p">(</span><span class="n">FinishGame</span><span class="p">)</span> <span class="n">finishGame</span><span class="p">})</span> <span class="p">{</span>
    <span class="p">...</span>
  <span class="p">}</span>

  <span class="n">R</span> <span class="n">whenOrElse</span><span class="p">&lt;</span><span class="n">R</span><span class="p">&gt;(</span>
      <span class="p">{</span><span class="n">FutureOr</span><span class="p">&lt;</span><span class="n">R</span><span class="p">&gt;</span> <span class="kt">Function</span><span class="p">(</span><span class="n">StartGame</span><span class="p">)</span> <span class="n">startGame</span><span class="p">,</span>
      <span class="n">FutureOr</span><span class="p">&lt;</span><span class="n">R</span><span class="p">&gt;</span> <span class="kt">Function</span><span class="p">(</span><span class="n">FinishGame</span><span class="p">)</span> <span class="n">finishGame</span><span class="p">,</span>
      <span class="nd">@required</span> <span class="n">FutureOr</span><span class="p">&lt;</span><span class="n">R</span><span class="p">&gt;</span> <span class="kt">Function</span><span class="p">(</span><span class="n">GameAction</span><span class="p">)</span> <span class="n">orElse</span><span class="p">})</span> <span class="p">{</span>
    <span class="p">...</span>
  <span class="p">}</span>

  <span class="n">FutureOr</span><span class="p">&lt;</span><span class="kt">void</span><span class="p">&gt;</span> <span class="n">whenPartial</span><span class="p">(</span>
      <span class="p">{</span><span class="n">FutureOr</span><span class="p">&lt;</span><span class="kt">void</span><span class="p">&gt;</span> <span class="kt">Function</span><span class="p">(</span><span class="n">StartGame</span><span class="p">)</span> <span class="n">startGame</span><span class="p">,</span>
      <span class="n">FutureOr</span><span class="p">&lt;</span><span class="kt">void</span><span class="p">&gt;</span> <span class="kt">Function</span><span class="p">(</span><span class="n">FinishGame</span><span class="p">)</span> <span class="n">finishGame</span><span class="p">})</span> <span class="p">{</span>
    <span class="p">...</span>
  <span class="p">}</span>

<span class="p">}</span>
</code></pre></div></div>

<p>Assuming we have an instance of <code class="language-plaintext highlighter-rouge">GameAction</code>, for example created using <code class="language-plaintext highlighter-rouge">GameAction.startGame()</code>, we have <strong>three ways</strong> to “switch” over the cases:</p>

<ul>
  <li>by calling <code class="language-plaintext highlighter-rouge">action.when(startGame: ..., finishGame: ...)</code>, passing to each parameter a block that accepts the incoming action with its parameters;</li>
  <li>by calling <code class="language-plaintext highlighter-rouge">action.whenOrElse(..., orElse: ...)</code>, optionally including blocks for each action and also including an <code class="language-plaintext highlighter-rouge">orElse</code> block that works like <code class="language-plaintext highlighter-rouge">default</code> in a regular <code class="language-plaintext highlighter-rouge">switch</code> statement;</li>
  <li>by calling <code class="language-plaintext highlighter-rouge">action.whenPartial(...)</code>, optionally including blocks for each statement, with no <code class="language-plaintext highlighter-rouge">orElse</code>.</li>
</ul>

<p>By using the first of these, we can make sure all cases are handled, and just as before we’ll get a compiler warning if anything is missing!</p>

<h3 id="putting-it-into-practice">Putting it into practice</h3>

<p>Let’s say that an action has been dispatched to the store:</p>

<div class="language-dart highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">store</span><span class="o">.</span><span class="na">dispatch</span><span class="p">(</span><span class="n">GameAction</span><span class="o">.</span><span class="na">finishGame</span><span class="p">(</span><span class="nl">finalScore:</span> <span class="mi">100</span><span class="p">));</span>
</code></pre></div></div>

<p>In our reducer, we obtain the next state by calling:</p>

<div class="language-dart highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">state</span> <span class="o">=</span> <span class="p">(</span><span class="n">action</span> <span class="k">as</span> <span class="n">GameAction</span><span class="p">)</span><span class="o">.</span><span class="na">when</span><span class="p">(</span>
  <span class="nl">startGame:</span> <span class="p">(</span><span class="n">_</span><span class="p">)</span> <span class="o">=</span><span class="p">&gt;</span> <span class="n">state</span><span class="o">.</span><span class="na">copyWith</span><span class="p">(</span><span class="nl">inProgress:</span> <span class="kc">true</span><span class="p">),</span>
  <span class="nl">finishGame:</span> <span class="p">(</span><span class="n">finishGameAction</span><span class="p">)</span> <span class="o">=</span><span class="p">&gt;</span> <span class="n">state</span><span class="o">.</span><span class="na">next</span><span class="p">(</span>
    <span class="nl">finalScore:</span> <span class="n">finishGameAction</span><span class="o">.</span><span class="na">finalScore</span><span class="p">,</span> 
    <span class="nl">inProgress:</span> <span class="kc">false</span>
  <span class="p">)</span>
<span class="p">);</span>
</code></pre></div></div>

<blockquote>
  <p>Note that <code class="language-plaintext highlighter-rouge">when</code> returns the value it got from the block that was called. Hence we can assign the result directly to the <code class="language-plaintext highlighter-rouge">state</code> value!</p>
</blockquote>

<p>This satisfies both of our requirements:</p>

<ul>
  <li>We got a <code class="language-plaintext highlighter-rouge">finalScore</code> out of the finish game action and applied it to our state.</li>
  <li>The compiler is still helping us. If we’d neglected to handle <code class="language-plaintext highlighter-rouge">startGame</code> or <code class="language-plaintext highlighter-rouge">finishGame</code>, we’d get a warning.</li>
</ul>]]></content><author><name>craig</name></author><category term="flutter" /><category term="programming" /><summary type="html"><![CDATA[The Super Enum package is good for Redux actions and more.]]></summary></entry><entry><title type="html">On state management in Flutter</title><link href="https://handform.net/2020/05/01/on-state-management-in-flutter.html" rel="alternate" type="text/html" title="On state management in Flutter" /><published>2020-05-01T00:00:00+00:00</published><updated>2020-05-01T00:00:00+00:00</updated><id>https://handform.net/2020/05/01/on-state-management-in-flutter</id><content type="html" xml:base="https://handform.net/2020/05/01/on-state-management-in-flutter.html"><![CDATA[<p>We’re almost ready to start coding our Flutter app. Where do we begin?</p>

<h3 id="model-view-confusion">Model, View, Confusion</h3>

<p>One of the most difficult and time-consuming aspects of app development is managing state.</p>

<p>Traditionally, app developers have followed the approach known as <strong>Model View Controller</strong>. We created hierarchies of views, bound them to variables in controller classes, and carefully updated those views whenever data in the underlying model changed. If the presence of some data in a view depended on ten different conditions, then we had to remember to update it whenever any one of those conditions changed. As our apps grew more advanced, they started incorporating all manner of unpredictable potential state changes, especially from asynchronous and background events, and we struggled to keep up.</p>

<p>Most of the pioneering work in trying to solve this problem has come from our web developer friends, and it’s from their world that we’ve seen the rise of the “reactive” programming style, in which the relationships between data are described statically, and changes propagate automatically through these relationships. It’s often compared to a spreadsheet containing formulae, where changing the value in one cell can trigger a propagation of changes to anywhere else in the sheet. It’s also a style being rapidly adopted by Apple in <a href="https://developer.apple.com/tutorials/swiftui/">SwiftUI</a> and by Google with <a href="https://developer.android.com/topic/libraries/data-binding">Data Bindings</a>.</p>

<h3 id="flutter-feelsreactive">Flutter feels reactive</h3>

<p>Flutter makes it virtually impossible to work in the traditional MVC approach I’ve described above, and very straightforward indeed to adopt some form of reactive programming.</p>

<p>That’s because it treats the entire UI hierarchy as a tree of lightweight views-<em>widgets</em> in the Flutter vernacular-that’s entirely bound to some state. When the state changes, any part of the tree that represents it must be rebuilt, and the tree gets very deep because the standard way of applying padding, alignment, and even styling is via nesting widgets inside others that confer these properties and do nothing else. Here’s an example of a simple row with a Text widget and some padding.</p>

<div class="language-dart highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">Padding</span><span class="p">(</span>
  <span class="nl">child:</span> <span class="n">Row</span><span class="p">(</span>
  <span class="nl">children:</span> <span class="p">&lt;</span><span class="n">Widget</span><span class="p">&gt;[</span>
    <span class="n">Text</span><span class="p">(</span><span class="n">user</span><span class="o">.</span><span class="na">name</span><span class="p">)</span>
  <span class="p">],</span>
<span class="p">))</span>
</code></pre></div></div>

<p>There’s no obvious way to get a reference to that innermost <code class="language-plaintext highlighter-rouge">Text</code> widget, so how do we update it? The answer is that we make a change to <code class="language-plaintext highlighter-rouge">user.name</code>, and trigger a rebuild of the widget tree. It seems wasteful, but Flutter renders its views itself rather than relying on any native UI SDK, and its authors have optimised it to work in this way. It works very well!</p>

<h3 id="deciding-how-not-to-doit">Deciding how not to do it</h3>

<p>In Flutter, basic state management is achieved using a function called <code class="language-plaintext highlighter-rouge">setState()</code>, which you call to rebuild a widget once the data underlying its properties have changed. This suffices for many, if not most apps, and it’s <a href="https://medium.com/flutter-community/flutter-state-management-setstate-fn-is-the-easiest-and-the-most-powerful-44703c97f035">more powerful</a> than many give it credit for.</p>

<p>But to me, it feels like we’re doing unnecessary work. If we’re aiming for a reactive programming style, I shouldn’t have to tell my widgets when their underlying data has changed. It’s also not trivial to update widgets that aren’t direct descendants of where you’re calling <code class="language-plaintext highlighter-rouge">setState()</code>: you need to implement callbacks, which feels like all the passing-around-delegates we traditionally had to do on iOS. You can’t entirely discard <code class="language-plaintext highlighter-rouge">setState()</code>; I’m using it in some widgets, primarily where I need animation or “micro-states” like UI interaction effects. But we’re <a href="https://flutter.dev/docs/development/data-and-backend/state-mgmt/options">truly spoiled for choice</a> when it comes to alternative state management patterns in Flutter, so we needn’t settle!</p>

<p><a href="https://pub.dev/packages/scoped_model"><strong>Scoped Model</strong></a> is a simple way of passing model data down to widgets, but I didn’t like the approach of having each view model be responsible for “broadcasting” that its data has changed, via the <code class="language-plaintext highlighter-rouge">notifyListeners()</code> function.
Google, for its part, recommends us to consider the <strong>BLoC pattern</strong> for complex apps. I won’t go into it here, but you can find <a href="https://medium.com/flutterpub/architecting-your-flutter-project-bd04e144a8f1">nice tutorials online</a>. My objection to it is that it appears to require too many manual steps, including a need to override Flutter’s <code class="language-plaintext highlighter-rouge">dispose()</code> method. It also pushes you to use RxDart, which is to my eye <a href="https://medium.com/flutter-community/why-use-rxdart-and-how-we-can-use-with-bloc-pattern-in-flutter-a64ca2c7c52d">overly complicated</a>.</p>

<p>Perhaps in my rejection of BLoC and RxDart you can sense that I’m not comfortable with the “extremes” of reactive programming. I find it hard to conceptualise an app as a confluence of data streams flowing and intersecting, and easier to think of it as an entity which presents to the user one of several discrete states, between which there are predictable and easy-to-understand transitions backed by business logic.
It so happens that there is a state management pattern which models apps just like this, and it’s called <strong>Redux</strong>.</p>

<h3 id="choosing-redux">Choosing Redux</h3>

<p>There are <a href="https://blog.novoda.com/introduction-to-redux-in-flutter/">great explanations of Redux</a> all over the Internet so I won’t get too deeply into this, but the main idea is that you bind your UI to the properties of a <em>state</em> object that’s simply representation—no logic—and apply changes to the state in functions called <em>reducers</em>. Reducers are “pure”, which means that given the same inputs they always produce the same output. The inputs to a reducer are simply the state itself and an <em>action</em> which indicates what business logic has to be performed. The output is a new and changed copy of the state. The state and reducers are both registered with a <em>store</em> which is responsible for passing actions to reducers and—since this is Flutter—triggering rebuilds of the widget tree on state changes. The widgets for their part observe properties of the state and dispatch actions to the store.</p>

<p>It looks complicated, but it boils down to some pretty simple principles, and might be represented thusly:</p>

<p><img class="materialboxed responsive-img" src="/assets/images/redux-explainer.png" /></p>

<p>The advantages are:</p>

<ul>
  <li>predictable journey from widget action to state change, and from state change to view update;</li>
  <li>it’s clear what bits go where: I don’t need to dive deep into my widget tree to find where the business logic is hidden, because I know it’s all in the reducers;</li>
  <li>since states are copied rather than mutated, it’s trivial to log all state changes when they pass out of reducers and even <a href="https://github.com/brianegan/flutter_redux_dev_tools">“time travel” through past states</a> for debugging purposes;</li>
  <li>being able to dispatch actions from anywhere in the widget tree liberates us from the need for delegates and callbacks.</li>
</ul>

<h3 id="applying-redux">Applying Redux</h3>

<p>First up, we need a Redux implementation for Flutter. The de facto standard at the moment is the <a href="https://github.com/brianegan/flutter_redux">Flutter Redux library by Brian Egan</a> (he’s also responsible for Scoped Model and about a million other Dart packages and is generally just a Very Smart Guy). Here’s a nice tutorial which I found very helpful: <a href="https://flutterbyexample.com/redux-app-getting-to-start">https://flutterbyexample.com/redux-app-getting-to-start</a>.</p>

<h3 id="project-structure">Project structure</h3>

<p>Here’s the structure I’ve opted for:</p>

<p><img class="materialboxed responsive-img" src="/assets/images/redux-structure.png" /></p>

<p>Some decisions made here were:</p>

<ul>
  <li>
    <p>A folder for Redux-specific parts of the app, but excluding state, which comprises dumb model objects with some convenient copying methods. Keeping state away from the rest of the app removes the temptation to add any “intelligence” there, and keeps the code clean if I ever want to switch away from Redux to another architecture.</p>
  </li>
  <li>
    <p>In Flutter everything is a widget, but for ease of code navigation I chose to treat some top-level widgets as “screens”, and to put these in a separate folder.</p>
  </li>
</ul>

<h3 id="the-first-screen-plusredux">The first screen, plus Redux</h3>

<p>The opening screens of the app I’m working on display a navigable hierarchy of “challenges”—quizzes on different aspects of the Chinese language—that are organised into groups and above that difficulty levels. All of this data has to be loaded from a JSON file.</p>

<p>Flutter supports performing the necessary file operations asynchronously (we’re going to copy it from the app’s assets into its documents folder), so the final problem is how to perform background work from Redux.</p>

<p>There are a few solutions and the simplest is to use <em>middleware</em>. <a href="https://redux.js.org/advanced/middleware">Middleware</a> is commonly encountered in Redux-based applications where some action has to take place that won’t affect the state—this is known as a “side effect”—or might cause the state to change but only later (like a network request). Middlewares (for there can be as many as you need) see every dispatched action and have the chance to do something with it, but won’t ever modify the app state themselves.</p>

<p>We’re going to write an <code class="language-plaintext highlighter-rouge">AssetsMiddleware</code> class that prepares the data structures we need to display the hierarchy of levels, groups and quizzes.</p>

<div class="language-dart highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">class</span> <span class="nc">AssetsPrepareLevelsAction</span> <span class="p">{</span> <span class="p">}</span>

<span class="kd">class</span> <span class="nc">AssetMiddleware</span> <span class="kd">implements</span> <span class="n">MiddlewareClass</span><span class="p">&lt;</span><span class="n">AppState</span><span class="p">&gt;</span> <span class="p">{</span>

  <span class="kd">final</span> <span class="kt">String</span> <span class="n">pathToAssets</span><span class="p">;</span>

  <span class="n">AssetMiddleware</span><span class="p">(</span><span class="k">this</span><span class="o">.</span><span class="na">pathToAssets</span><span class="p">);</span>
  
  <span class="nd">@override</span>
  <span class="n">Future</span> <span class="n">call</span><span class="p">(</span><span class="n">Store</span><span class="p">&lt;</span><span class="n">AppState</span><span class="p">&gt;</span> <span class="n">store</span><span class="p">,</span> <span class="n">action</span><span class="p">,</span> <span class="n">NextDispatcher</span> <span class="n">next</span><span class="p">)</span> <span class="kd">async</span> <span class="p">{</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">action</span> <span class="k">is</span> <span class="n">AssetsPrepareLevelsAction</span><span class="p">)</span> <span class="p">{</span>
      <span class="kt">String</span> <span class="n">pathToLevels</span> <span class="o">=</span> <span class="k">await</span> <span class="n">Asset</span><span class="p">(</span><span class="s">"</span><span class="si">$pathToAssets</span><span class="s">/levels"</span><span class="p">,</span> <span class="s">"levels"</span><span class="p">)</span><span class="o">.</span><span class="na">prepare</span><span class="p">();</span>
      <span class="kt">String</span> <span class="n">levelsString</span> <span class="o">=</span> <span class="k">await</span> <span class="n">File</span><span class="p">(</span><span class="n">pathToLevels</span><span class="p">)</span><span class="o">.</span><span class="na">readAsString</span><span class="p">();</span>
      <span class="kt">List</span><span class="p">&lt;</span><span class="kd">dynamic</span><span class="p">&gt;</span> <span class="n">levelsJson</span> <span class="o">=</span> <span class="n">jsonDecode</span><span class="p">(</span><span class="n">levelsString</span><span class="p">);</span>
      <span class="n">store</span><span class="o">.</span><span class="na">dispatch</span><span class="p">(</span><span class="n">LoadLevelsAction</span><span class="p">(</span><span class="n">Level</span><span class="o">.</span><span class="na">levelHeirarchyFromJson</span><span class="p">(</span><span class="n">levelsJson</span><span class="p">)));</span>
    <span class="p">}</span>
    <span class="n">next</span><span class="p">(</span><span class="n">action</span><span class="p">);</span> <span class="c1">// don't forget, since other middlewares might look at this action</span>
    <span class="p">}</span>    
  <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>If you’re curious about <code class="language-plaintext highlighter-rouge">Asset</code>, you can see that <a href="https://gist.github.com/craigomac/a134095b8051ed40910fe17b1700598e">in this Gist</a>.</p>

<p>Here’s how the main entry point into the app looks now:</p>

<div class="language-dart highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">void</span> <span class="nf">main</span><span class="p">()</span> <span class="p">{</span>
  <span class="kd">final</span> <span class="n">store</span> <span class="o">=</span> <span class="k">new</span> <span class="n">Store</span><span class="p">&lt;</span><span class="n">AppState</span><span class="p">&gt;(</span>
      <span class="n">AppStateReducer</span><span class="p">(),</span>
      <span class="nl">initialState:</span> <span class="n">AppState</span><span class="o">.</span><span class="na">initial</span><span class="p">(),</span>
      <span class="nl">middleware:</span> <span class="p">[</span>
        <span class="n">AssetMiddleware</span><span class="p">(</span><span class="s">"assets"</span><span class="p">),</span>
        <span class="n">AudioMiddleware</span><span class="p">(),</span>        
      <span class="p">]);</span>

  <span class="n">runApp</span><span class="p">(</span><span class="k">new</span> <span class="n">App</span><span class="p">(</span>
    <span class="nl">store:</span> <span class="n">store</span><span class="p">,</span>
  <span class="p">));</span>

  <span class="n">store</span><span class="o">.</span><span class="na">dispatch</span><span class="p">(</span><span class="n">AssetsPrepareLevelsAction</span><span class="p">());</span>
<span class="p">}</span>
</code></pre></div></div>

<p>You can see that there’s another middleware class here named <code class="language-plaintext highlighter-rouge">AudioMiddleware</code>: playing audio files is another good candidate for middleware since it produces plenty of side effects!</p>

<p>The middleware picks up the <code class="language-plaintext highlighter-rouge">AssetsPrepareLevelsAction</code>, prepares the level data and finally dispatches <code class="language-plaintext highlighter-rouge">LoadLevelsAction</code>, which is handled by a reducer to update the app state so that our widget tree can display the loaded levels.</p>

<p>Phew!</p>

<h3 id="next-steps">Next steps</h3>

<p>Next time, we’ll take a look at some other ways you can improve your Redux workflow in Flutter. Stay tuned!</p>]]></content><author><name>craig</name></author><category term="flutter" /><category term="programming" /><summary type="html"><![CDATA[And why you might want to consider Redux.]]></summary></entry></feed>