<?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 Tobias Ottenweller on Medium]]></title>
        <description><![CDATA[Stories by Tobias Ottenweller on Medium]]></description>
        <link>https://medium.com/@tobi-86596?source=rss-3733f959c7ce------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*8qZ1dq31HN8iCi4g4FjZLw.jpeg</url>
            <title>Stories by Tobias Ottenweller on Medium</title>
            <link>https://medium.com/@tobi-86596?source=rss-3733f959c7ce------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 20:21:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tobi-86596/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[Why precision matters — Decimals in Dart/Flutter]]></title>
            <link>https://tobi-86596.medium.com/why-precision-matters-decimals-in-dart-flutter-aab33a56fc27?source=rss-3733f959c7ce------2</link>
            <guid isPermaLink="false">https://medium.com/p/aab33a56fc27</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[decimal]]></category>
            <category><![CDATA[dart]]></category>
            <dc:creator><![CDATA[Tobias Ottenweller]]></dc:creator>
            <pubDate>Sun, 06 Jul 2025 16:19:13 GMT</pubDate>
            <atom:updated>2025-07-06T16:19:13.455Z</atom:updated>
            <content:encoded><![CDATA[<h3>Why precision matters — Decimals in Dart/Flutter</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Lut2R31ChUdBxMepXE1DQ.png" /></figure><p>As a fellow app developer, you know that writing software can be hard — bugs keep popping up, or a third-party API just isn’t doing what you want. But at least simple mathematical operations work, right?</p><p>Not always. Did you know that adding two numbers together in Dart (and most other languages) might not give you the result you expected?</p><p>Give it a try yourself. Here is the most famous and simple example:</p><pre>print(0.1 + 0.2);</pre><p>This should print “0.3” — but actually, we get “0.30000000000000004”.</p><p>By the end of this article, you’ll understand why decimal calculations can be tricky in Dart and how to handle them correctly to avoid bugs in your Flutter apps.</p><p>Let’s get back to the example from above. Not a big deal, you might think — let’s just round to make the value look fine. Anyway, we should use a NumberFormat from the intl package to properly localize numbers. So, to display some monetary amount, we might use:</p><pre>final numberFormat = NumberFormat(&quot;#0.00&quot;, &quot;en_US&quot;);<br>print(numberFormat.format(0.1 + 0.2));</pre><p>And it gives us the correct output of “0.30”.</p><p>But besides just “displaying” issues, we also might run into actual problems in your business logic. Here is a snippet emulating a shopping basket. There is a 50 Euro minimum order value. In the basket, we have a pair of jeans, a t-shirt, and socks. These should add up to exactly 50 Euro.</p><pre>final jeans = 24.99;<br>final tShirt = 15.50;<br>final socks = 9.51;<br>  <br>final total = jeans + tShirt + socks;<br>  <br>if (total &lt; 50) {<br>  print(&#39;Add more items to reach 50 Euro minimum order value&#39;);<br>}<br>  <br>print(total); // should output 50, does 49.99999999999999</pre><p>Again, the standard floating point numbers don’t work properly. Running this will print the message about adding more items to the basket.</p><p>Hopefully, this convinces everyone that standard Dart types aren’t suitable when precise calculations are needed — especially in cases like this one involving monetary values.</p><h3>Floating Points Numbers</h3><p>Above, I mentioned floating point numbers. But what are they?</p><p>Floating point numbers are how computers store decimal values like 3.14 or 0.001. Unlike integers, which only store whole numbers, floating point numbers use a special format that lets the “decimal point” move or “float” to different positions. Think of it like scientific notation — instead of writing 12,345,000 you can write 1.2345 × 1⁰⁷. Computers do something similar but in binary, allowing to store really large (or small) numbers without needing too much memory.</p><p>In Dart and Flutter, our standard double is exactly such a data type.</p><blockquote>If this got you hooked, look at how numbers in Dart are <a href="https://dart.dev/resources/language/number-representation">represented</a> and read the <a href="https://en.wikipedia.org/wiki/IEEE_754">IEEE 754</a> standard that makes a <a href="https://api.dart.dev/dart-core/double-class.html">double</a> work.</blockquote><h3>Why Floating Point Arithmetic Fails for Decimals</h3><p>Before we look into solving this issue, let’s discuss why this is happening.</p><p>Computers work in binary, so all numbers we input into our program must be converted from the decimal system we use in our day-to-day life to binary. And this reveals very specific implications.</p><p>Like in decimal, binary can represent some numbers easily while others are hard to represent. The fraction 1/3 in decimal is a perfect example. Expressing it as a fraction is easy, but in decimal representation, it always loses some precision. There is an infinite number of 3s behind the zero (0.33333333333…).</p><p>In binary, the same thing is happening, but with completely different numbers. You might have guessed it — decimal 0.1 is very hard to represent in binary and results in an infinite length number (0.0001100110011…).</p><p>And this is the root cause of some numbers not matching our expectations, as a computer is converting back and forth between binary and decimal.</p><p>You, of course, can mitigate the issue by storing numbers with a high amount of decimal places. But we still don’t have infinite memory and processing power. And that’s why “standard” data types like double will produce these “errors”.</p><h3>How to use Decimal data types in Dart</h3><p>So how do we overcome these issues? Meet <a href="https://pub.dev/packages/big_decimal">BigDecimal</a>, a library supporting arbitrary precision on numbers.</p><p>Let’s start by recreating the example from above:</p><pre>final jeans = BigDecimal.parse(&#39;24.99&#39;);<br>final tShirt = BigDecimal.parse(&#39;15.50&#39;);<br>final socks = BigDecimal.parse(&#39;9.51&#39;);<br><br>final total = jeans + tShirt + socks;<br><br>if (total &lt; BigDecimal.parse(&#39;50&#39;)) {<br>   print(&#39;Add more items to reach 50 Euro minimum order value&#39;);<br>}<br><br>print(total); // outputs 50.00</pre><p>First of all, this outputs 50.00 properly and won’t warn us about too few items in the basket. Next, you might notice that decimals are constructed with strings. This makes sure we don’t have precision issues when creating the objects. It also opens up an easy way to send and receive “correct” numbers over, e.g., a REST API.</p><blockquote><strong>Why BigDecimal, I see many packages for decimals in Dart.</strong> You are absolutely right. I like BigDecimal as a project because it is stable, highly performant and based on a battle tested Java implementation. But do your own research! A good start is looking at this <a href="https://github.com/vi-k/yet_another_decimal?tab=readme-ov-file#why">comparison</a>.</blockquote><h4>How does BigDecimal work</h4><p>Internally, a BigDecimal object operates over <a href="https://github.com/bugless/big-decimal/blob/main/lib/src/big_decimal.dart#L115">2 properties</a>, an <em>intVal</em> and <em>scale</em>.</p><p>These two describe the value we store while avoiding any lossy storage. Our desired value will always get stored as an integer, while the scale defines where the decimal point goes. To give you some examples, 9.99 becomes 999 with a scale of 2, while 0.939 becomes 939 with a scale of 3.</p><p>Note that the integer is not a normal int, but rather <a href="https://api.flutter.dev/flutter/dart-core/BigInt-class.html">BigInt</a>, a datatype that, just like BigDecimal allows storing arbitrarily large numbers.</p><p>On top of these properties comes logic to perform basic operations like addition or multiplication. This allows us to use BigDecimals “just” like doubles in your business logic. As these are implemented to work with scale and intVal, no problems arise due to the “binary representation” of decimals.</p><blockquote><strong>Should I now always use BigDecimal instead of double</strong>? Surely not. For most logic and operations we perform in our apps, using doubles is plenty good. Decimal types have a huge performance penalty compared to standard floating point types. Use them only when dealing with monetary, financial, or other operations where correctness is an issue.</blockquote><p>Lastly, we need to talk about rounding. Even though BigDecimal can work with arbitrary precision, you do not want to store infinitely long numbers — 1/3 still results in an infinitely long decimal number. This means when performing certain operations, like division, we must provide rounding and scaling information:</p><pre>final one = BigDecimal.one;<br>final three = BigDecimal.parse(&#39;3&#39;);<br><br>final oneThird = one.divide(<br>   three, <br>   roundingMode: RoundingMode.HALF_UP, <br>   scale: 10,<br>)</pre><p><em>Rounding mode </em>should be self-explanatory, while <em>scale</em> defines how precise we want to be. Setting scale to 2 gives us 0.33, while a scale at 10 gives us 0.3333333333.</p><h3>Bonus: Formatting Decimals</h3><p>Now that you know how to properly use decimal data types in your business logic, you might want to show them to the user. To properly localize the numbers, you are most likely already using the <a href="https://pub.dev/packages/intl#number-formatting-and-parsing">intl package</a>. But, out of the box, there is no support for decimal types. For this, I wrote a little package that bridges the gap between intl and big_decimal. It is called <a href="https://pub.dev/packages/big_decimal_intl">big_decimal_intl</a> a and allows using any number format of intl to format or parse decimals.</p><p>Here is a little example:</p><pre>final format = NumberFormat.currency(<br>    locale: &#39;de_DE&#39;, <br>    name: &#39;EUR&#39;,<br>);<br>final formatter = BigDecimalFormatter(format);<br><br>// next line prints: 100.000,00 EUR<br>print(formatter.format(BigDecimal.parse(&#39;100000&#39;))); <br><br>// next line prints: 100000.00<br>print(formatter.parse(&#39;100.000&#39;)); </pre><p>To format decimal numbers, just create any `NumberFormat` object depending on your needs. Afterwards, create a BigDecimalFormatter. It acts as a wrapper around the number format object, enabling formatting and parsing of `BigDecimal` objects.</p><p>And this wraps up our introduction to decimal numbers in Dart and Flutter. By understanding how number types work and where precision matters, you’ll be better equipped to handle calculations smoothly — whether it’s for finances, measurements, or any situation where accuracy counts.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aab33a56fc27" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter — the Good, the Bad and the Ugly (Part 2)]]></title>
            <link>https://medium.com/wayvs-tech/flutter-the-good-the-bad-and-the-ugly-part-2-4e776a96bb41?source=rss-3733f959c7ce------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e776a96bb41</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <dc:creator><![CDATA[Tobias Ottenweller]]></dc:creator>
            <pubDate>Fri, 20 May 2022 18:02:24 GMT</pubDate>
            <atom:updated>2022-05-20T18:02:24.697Z</atom:updated>
            <content:encoded><![CDATA[<h3><a href="https://medium.com/p/2403467d23e9/edit?source=your_stories_page-------------------------------------">Flutter — the Good, the Bad and the Ugly (Part 2)</a></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HxtQhzaaAH7KEhcwuzL12w.png" /></figure><p>In this mini-series, you will get the perspective of an experienced native iOS developer on spending almost one-year building and releasing a Flutter app. Of course, the presented topics are purely subjective — your experience might vary.</p><p>When the team decided to switch to Flutter, no one on our team had much experience writing code in Dart or using Flutter widgets to compose UI. So the following insight was gained during the development from a novice to becoming a somewhat experienced Flutter developer.</p><p>To already take away the conclusion: using Flutter is a success for us as we are continuing to build our mobile app using it. But where is light is also shadow. This series is about both.</p><p>If you now got interested in seeing what we have built? Follow this <a href="https://wayvs.app/">link</a>.</p><p><strong>In this part, I’m talking about the bad parts. Look out for parts </strong><a href="https://medium.com/@tobi-86596/flutter-the-good-the-bad-and-the-ugly-part-1-2403467d23e9"><strong>one</strong></a><strong> and </strong><a href="https://medium.com/@tobi-86596/flutter-the-good-the-bad-and-the-ugly-part-3-6359f2318101"><strong>three</strong></a><strong> about the good and ugly parts of developing Flutter applications.</strong></p><h3>The Bad</h3><h4>Dart</h4><p>As mentioned, Dart is easy to learn. But here, it already stops for me on the positive side. When coming from Swift, many things are annoying or make it easy to introduce bugs. Like missing automatic generated setters and getters for properties, missing default constructors with arguments, required parentheses for if and other statements. I could come up with a lot more points, but here will follow two more noteworthy points:</p><p><strong>Generics</strong><br>Often the type inference regarding generics is very limited. You have to write down the types of closures manually. It becomes apparent when using RxDart.</p><pre>final a = Stream.value(0);<br>final b = Stream.value(0);</pre><pre>final c = Rx.combineLatest2(a, b, (a, b) =&gt; a + b);</pre><p>Looking at the snippet, the compiler should be fine inferring all types here. We should get c to be of type Stream&lt;int&gt;. But no! a and b inside the closure are of type Object? and you have to add the correct generic parameters to the combineLatest call to make this snippet work.</p><p>Another issue with generics, well actually more the type system of Dart is that there is also no way to reference <a href="https://github.com/dart-lang/sdk/issues/28477">Self or </a><a href="https://github.com/dart-lang/sdk/issues/28477">This</a>, limiting the usefulness of the type system in many complex settings. We already ran multiple times into the problem of having to resort to some other solution or writing less type-safe code by just casting values.</p><p><strong>Limited Usefulness of Extensions</strong><br>Extensions are great. You can add functionality to existing types — even if those types are provided by some external library.</p><p>Adding instance methods to classes works as expected. Consider the following code snipped:</p><pre>class A {<br> A(this.a);<br> <br> int a;<br>}</pre><pre>extension Adder on A {<br> void add(int value) =&gt; a += value;<br>}</pre><p>With the Adder extension, you can now call add on any instance of A. This is nice, but more advanced uses of extensions are not supported: Adding (factory) constructs to classes using extensions is not allowed (something I use all the time with Swift). For a workaround, you might do something like this:</p><pre>extension Constructor on A {<br> // factory Adder.default() =&gt; A(0); &lt;- not supported!<br> static A fallback() =&gt; A(0);<br>}</pre><p>But now, instead of calling A.fallback() you need to call Constructor.fallback(). Defying the whole idea of adding functionality to classes using extensions. You could have just created a free function or auxiliary class for generating your custom constructor/factory.</p><h4>Strange gaps</h4><p>Back from Dart to Flutter, which offers tons of widgets to choose and customise in order to build your UI. Sometimes it is just hard to find the right widgets to do the job. But often, you will find functionality is just not supported out of the box. Here are two examples:</p><p><strong>Grouped Lists</strong><br>Often, you want to display a list of things grouped by some property. For example, show a list of people sorted in alphabetical order, having the first letter as a group header. A very common pattern you might think: not with Flutter.</p><p>The standard ListView widget shipping with Flutter does not support groups or group headers. There is, of course, some <a href="https://pub.dev/packages/grouped_list">third-party library</a> that adds this functionality. But still, I often wonder why this is not part of the standard Flutter widgets.</p><p><strong>Button States for iOS</strong><br>The same goes for CupertinoButton, where it is easy to define enabled and disabled colors. But adjusting the pressed state color is not so easy. Flutter assumes you will always want to make your button half-transparent when pressed. There is also no out-of-the-box way to change the button content for the disabled state (like using a different foreground color).<br>The Flutter team did not put so much love into their Cupertino buttons as they did for the Material counterparts. Since with ButtonStyle, you have a lot more control over buttons on the Android side.</p><blockquote>This was part two of the mini-series on Flutter. I hope you enjoyed it! You can continue reading in part <a href="https://medium.com/@tobi-86596/flutter-the-good-the-bad-and-the-ugly-part-3-6359f2318101">three</a>.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e776a96bb41" width="1" height="1" alt=""><hr><p><a href="https://medium.com/wayvs-tech/flutter-the-good-the-bad-and-the-ugly-part-2-4e776a96bb41">Flutter — the Good, the Bad and the Ugly (Part 2)</a> was originally published in <a href="https://medium.com/wayvs-tech">wayvs Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter — the Good, the Bad and the Ugly (Part 3)]]></title>
            <link>https://medium.com/wayvs-tech/flutter-the-good-the-bad-and-the-ugly-part-3-6359f2318101?source=rss-3733f959c7ce------2</link>
            <guid isPermaLink="false">https://medium.com/p/6359f2318101</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <dc:creator><![CDATA[Tobias Ottenweller]]></dc:creator>
            <pubDate>Fri, 20 May 2022 18:02:22 GMT</pubDate>
            <atom:updated>2022-05-20T18:02:22.281Z</atom:updated>
            <content:encoded><![CDATA[<h3><a href="https://medium.com/p/2403467d23e9/edit?source=your_stories_page-------------------------------------">Flutter — the Good, the Bad and the Ugly (Part 3)</a></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HxtQhzaaAH7KEhcwuzL12w.png" /></figure><p>In this mini-series, you will get the perspective of an experienced native iOS developer who has spent almost one-year building and releasing a Flutter app. Of course, the presented topics are purely subjective — your experience may vary.<br>When the team decided to switch to Flutter, no one had much experience writing code in Dart or used Flutter widgets to compose UI. The following insight was gained during the development from a novice to becoming a somewhat experienced Flutter developer.<br>Spoiler alert: using Flutter is a successful environment for us as we use it to continue building our mobile app. But where there is light, also a shadow! This series is about both.</p><p>If you’re interested in seeing what we have built? Check it out with this <a href="https://wayvs.app/">link</a>.</p><p><strong>In this part, I’m talking about the good parts. Look out for parts </strong><a href="https://medium.com/@tobi-86596/flutter-the-good-the-bad-and-the-ugly-part-1-2403467d23e9"><strong>one</strong></a><strong> and </strong><a href="https://medium.com/@tobi-86596/flutter-the-good-the-bad-and-the-ugly-part-2-4e776a96bb41"><strong>two</strong></a><strong> about the good and bad of developing Flutter applications.</strong></p><h3>The Ugly</h3><h4>Exceptions and Errors</h4><p>Things might go wrong. Almost all programming languages provide ways for error handling. Dart is no exception here, allowing to throw something that you can catch further up in the call hierarchy.</p><p>I would assume that only exceptions (or whatever your programming language is calling them) can be thrown. Not with Dart. Everything can be thrown: strings, integers, even custom objects. A poor design choice! There is a <a href="https://dart.dev/tools/linter-rules#only_throw_errors">linter rule</a> for disallowing throwing of any object. But why allow it in the first place?</p><p>Besides Exceptions there are also Errors. Exceptions indicate failures at runtime that are part of normal operation, while errors indicate failures the programmer did. That is fine! But by default, all try/catch statements will catch both errors and exceptions, making it very easy to ignore or shadow programming errors, having them look like normal runtime failures. There are again linter rules for catching <a href="https://dart.dev/tools/linter-rules#avoid_catching_errors">only exceptions</a>, but why not have sensible defaults for try/catch that would require adding code to catch errors (or anything else that might get thrown)?</p><h4>Native Plugins</h4><p>Coming from native development and seeing the quality of native code written to bridge functionality to Flutter makes me shiver.<br>I’m not going to point fingers, but things look bad: from missing error handling to having many warnings to comparing pointer addresses instead of string content. Sure, people writing those plugins might only have limited experience with native mobile development, nevertheless including those plugins come with a risk of breaking things.<br>We resorted to writing some native plugins on our own, making sure they actually work and are up to our standard.</p><h3>Conclusion</h3><p>Flutter is no silver bullet when it comes to mobile app development. Nevertheless, having limited resources or small to medium projects, I recommend looking into Flutter. With an active community around it and good enough widgets, libraries and documentation, you can get pretty far. You might save a lot of time not having to write two separate code bases for Android and iOS. But keep in mind the more complex setups, that also want to take in platform-specific behavior, might give you a hard time and require workarounds and a little native code for support.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6359f2318101" width="1" height="1" alt=""><hr><p><a href="https://medium.com/wayvs-tech/flutter-the-good-the-bad-and-the-ugly-part-3-6359f2318101">Flutter — the Good, the Bad and the Ugly (Part 3)</a> was originally published in <a href="https://medium.com/wayvs-tech">wayvs Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter — the Good, the Bad and the Ugly (Part 1)]]></title>
            <link>https://medium.com/wayvs-tech/flutter-the-good-the-bad-and-the-ugly-part-1-2403467d23e9?source=rss-3733f959c7ce------2</link>
            <guid isPermaLink="false">https://medium.com/p/2403467d23e9</guid>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Tobias Ottenweller]]></dc:creator>
            <pubDate>Fri, 20 May 2022 18:02:22 GMT</pubDate>
            <atom:updated>2022-05-20T18:02:22.187Z</atom:updated>
            <content:encoded><![CDATA[<h3>Flutter — the Good, the Bad and the Ugly (Part 1)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HxtQhzaaAH7KEhcwuzL12w.png" /></figure><p>In this mini-series, you will get the perspective of an experienced native iOS developer who has spent almost one-year building and releasing a Flutter app. Of course, the presented topics are purely subjective — your experience may vary.<br>When the team decided to switch to Flutter, no one had much experience writing code in Dart or used Flutter widgets to compose UI. The following insight was gained during the development from a novice to becoming a somewhat experienced Flutter developer.<br>Spoiler alert: using Flutter is a successful environment for us as we use it to continue building our mobile app. But where there is light, also a shadow! This series is about both.</p><p>If you’re interested in seeing what we have built? Check it out with this <a href="https://wayvs.app/">link</a>.</p><p><strong>In this part, I’m talking about the good parts. Look out for parts </strong><a href="https://medium.com/@tobi-86596/flutter-the-good-the-bad-and-the-ugly-part-2-4e776a96bb41"><strong>two</strong></a><strong> and </strong><a href="https://medium.com/@tobi-86596/flutter-the-good-the-bad-and-the-ugly-part-3-6359f2318101"><strong>three</strong></a><strong> about the bad and ugly of developing Flutter applications.</strong></p><h3>The Good</h3><h4>Widgets and the Widget Tree</h4><p>The idea of everything being a widget keeps concepts simple and easy to understand. Organizing UI, navigation, and state all as widgets is an almost perfect approach.</p><blockquote>What makes the concept of the widget tree so powerful is the ability to build complex UI out of many tiny widgets. While being able to compose and rearrange them without a hassle, they continue to be clear and maintainable.</blockquote><p>In practice, it worked out very well. During a short ramp-up phase where we ended up in extremely large single widgets (containing all the UI of a whole screen), we figured out how to build UI composed of small widgets.</p><h4>State handling</h4><p>The flutter community came up with some brilliant ways of handling state for your UI. You can use stateful widgets, inherited widgets, BLoC, and many other approaches. Most of them implement a reactive approach, eliminating the stale UI problem that often introduces bugs and strange behavior into mobile apps.</p><p>When starting with Flutter, choosing the right approach for your app can be overwhelming. In the end, we settled on Riverpod since it allowed us to separate UI from business logic nicely. It also let us apply some best practices from the MVVM pattern we use in native development. (If you are interested in the details: a view model does more or less reassemble the state of a state notifier here.)</p><p>However, the state management pattern you should use depends a lot on the needs of your app. And having a choice is a good thing!</p><h4>Learning curve</h4><p>We only spent about two weeks of research and learning before we started the actual development of our app. Getting into the basics and learning Dart as well as knowing the most common widgets can be achieved in very little time. That is especially true compared to learning Swift and UIKit or Kotlin and Android.</p><p>As an example, take your lists or <a href="https://stackoverflow.com/a/40584425">recycle</a>r /<a href="https://stackoverflow.com/a/33234181">table</a> views. Compare the linked examples with the following code snipped:</p><pre>class ListExample extends StatelessWidget {<br>  static final content = [&#39;Apple&#39;, &#39;Banana&#39;, &#39;Kiwi&#39;, &#39;Mango&#39;];</pre><pre><a href="http://twitter.com/override">@override</a><br>  Widget build(BuildContext context) {<br>    return ListView.builder(<br>      itemCount: content.length,<br>      itemBuilder: (_, index) =&gt; Text(content[index]),<br>    );<br>  }<br>}</pre><h4>Almost Native UI</h4><p>With a bit of effort, you can produce nearly native-looking UIs for both Android and iOS. (I can’t talk about how Flutter on the web or desktop is working, since I have no experience there.)</p><p>Of course there is some effort involved in getting native-looking widgets on both platforms. Our approach here is to build widgets that, depending on the platform, apply different values or return a completely different widget (sub-) tree. That makes it possible to combine those into a platform-agnostic widget that we use to compose the final UI.</p><p>If you look close enough, I’m sure you can always spot some tiny things that would look or work differently on native apps. Nevertheless, a regular user should not experience any negative impact from using a Flutter app in comparison to a native one.</p><blockquote>This was part one of the mini-series on Flutter. I hope you enjoyed it! You can continue reading in part <a href="https://medium.com/@tobi-86596/flutter-the-good-the-bad-and-the-ugly-part-2-4e776a96bb41">two</a>.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2403467d23e9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/wayvs-tech/flutter-the-good-the-bad-and-the-ugly-part-1-2403467d23e9">Flutter — the Good, the Bad and the Ugly (Part 1)</a> was originally published in <a href="https://medium.com/wayvs-tech">wayvs Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Troubleshooting Guide]]></title>
            <link>https://medium.com/wayvs-tech/flutter-troubleshooting-guide-c5eb5ccb595f?source=rss-3733f959c7ce------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5eb5ccb595f</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[troubleshooting]]></category>
            <category><![CDATA[clean]]></category>
            <category><![CDATA[cocoapods-keys]]></category>
            <category><![CDATA[pub]]></category>
            <dc:creator><![CDATA[Tobias Ottenweller]]></dc:creator>
            <pubDate>Fri, 09 Apr 2021 11:42:23 GMT</pubDate>
            <atom:updated>2021-06-17T13:00:36.109Z</atom:updated>
            <content:encoded><![CDATA[<p>We often run into problems after updating some dependencies, flutter itself, or changing some setup configuration. Various things might go wrong and block you from building a flutter app while your colleagues don’t have any problem.</p><p>With the following steps, so far we could fix most of the problems building and running a flutter application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*47-h9vVrJ_JN8Hd3TKwbig.png" /></figure><blockquote><strong>A word of caution</strong> – as always, don’t copy blindly commands into your terminal you find online. Try to understand what they are doing and read about them before executing them. Otherwise, you might lose precious data on your computer.</blockquote><h3>Validate your Flutter installation</h3><p>If you usually don’t build the project because you are working as QA or backend engineer, you should validate that you have the correct Flutter version installed first.</p><h4>Make sure the correct Flutter version is installed</h4><p>Check that you are on the correct Flutter channel:</p><pre>$ flutter channel stable|beta|dev|master</pre><p>Afterward update to the latest version:</p><pre>$ flutter upgrade --force</pre><p>Or you need a specific Flutter version to build the project downgrade a specific version:</p><pre>$ flutter downgrade v1.22.6</pre><h4>Run Flutter Doctor</h4><p>The first thing afterward should be checking if something is wrong with your flutter setup. With the following command you can check for common setup issues:</p><pre>$ flutter doctor</pre><h3>Restart Android Studio or Visual Studio Code</h3><p>“Did you try turning it off and on again?” — sounds stupid but helps very often. Something the IDEs just don’t realize that something has changed, e.g. after switching branch. It might help just restarting your IDE and trying again.</p><h3>Cleaning</h3><p>This command is most of the time enough to get you going again.</p><pre>$ flutter clean</pre><p>If that doesn’t help, you can also try cleaning manually.</p><pre>$ rm -rf build<br>$ rm -rf .packages <br>$ rm -rf .flutter-plugins</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*rJs3bSky3t1pAy9yTi3PTw.png" /><figcaption>everything seems broken after running flutter clean</figcaption></figure><h3>CocoaPods and Xcode</h3><p>When building for iOS, we found that often problems with CocoaPods. Sometimes you need to update the pod repos, sometimes re-creating the Xcode pods project. The following does everything:</p><pre>$ pod cache clean --all<br>$ rm -rf ios/.symlinks<br>$ rm -rf ios/Podfile.lock <br>$ rm -rf ios/Pods/<br>$ pod repo update</pre><p>There is also our friend derived data:</p><pre>$ rm -rf ~/Library/Developer/Xcode/DerivedData/*</pre><h3>Generate Auto-Generated Code</h3><p>If you use a database library like <a href="https://github.com/vitusortner/floor">floor</a>, that uses <a href="https://dart.dev/tools/build_runner">build runner</a>, use the following command to re-generate the dart source code:</p><pre>$ flutter packages pub run build_runner build --delete-conflicting-outputs</pre><p>Another thing might be to re-generate localizations if you use something like <a href="https://pub.dev/packages/intl_utils">intl utils</a>. For intl utils, use the following command:</p><pre>$ flutter pub run intl_utils:generate</pre><p>There are many other tools and libraries out there. And the project you are trying to run might use some of them. Please check your project and documentation on how to generate code for those libraries and tools.</p><h3>Repair the pub cache</h3><p>After updating flutter, we found that sometimes you need to repair your pub cache. Use the following command for this:</p><pre>$ flutter pub cache repair</pre><h3>Kill rogue Dart processes</h3><p>Unfortunately, sometimes a dart process will stick around in the background blocking you from building your flutter project. They might do things like generating localisations or creating auto-generated code and hang doing so or run with the wrong input or configuration.</p><p>So, looking for unwanted dart processes and killing them might help:</p><pre>$ killall -9 dart</pre><h3>Restart your computer</h3><p>If all above doesn’t help, restart your computer. A few times this resolved our build issues. There might be better ways of detecting and fixing issues, but as a last resort, this can work.</p><p>Thanks for reading and checking out this article. Hopefully, it helped you resolve the issues you were facing!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5eb5ccb595f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/wayvs-tech/flutter-troubleshooting-guide-c5eb5ccb595f">Flutter Troubleshooting Guide</a> was originally published in <a href="https://medium.com/wayvs-tech">wayvs Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Never run carthage bootstrap again]]></title>
            <link>https://tobi-86596.medium.com/never-run-carthage-bootstrap-again-c3a064c0b2f3?source=rss-3733f959c7ce------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3a064c0b2f3</guid>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[carthage]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[Tobias Ottenweller]]></dc:creator>
            <pubDate>Fri, 17 Apr 2020 07:23:16 GMT</pubDate>
            <atom:updated>2020-04-17T07:23:16.323Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/923/1*tvCaXhSaBwd8gK2_qbMp_w.png" /></figure><blockquote>The title is a bit clickbaity — hopefully, you continue reading anyway <em>🙂</em></blockquote><p>Ever got tired of running into bugs or build errors caused by an outdated dependency your colleague updated earlier? You don’t want to guide your PO, designer or Android developer how to install dependencies before hitting run in Xcode? Carthage Workflows will save you!</p><p>To automatically install dependencies, an option would be to just put carthage bootstrap --bootstrap --platform iOS --cache-builds into build phase script. So Xcode will run it every time you build. But bootstrapping takes some time, even when everything is actually up to date. For example, running bootstrap one of our current projects with 12 dependencies takes over 50 seconds to complete.</p><p>But thankfully this can be much improved. There is a repository with <a href="https://github.com/Carthage/workflows">opinionated workflows built on top of Carthage</a> containing a carthage-verify script that does exactly what we want — without performing any long-running tasks.</p><p>Just add the linked repository as a submodule to your project (or copy the verify script if you are super lazy). Then, add a run script build-phase with the following content:</p><pre>./carthage-workflows/carthage-verify --no_skip_missing</pre><pre>if [ &quot;$?&quot; -ne &quot;0&quot; ]; then<br>    carthage bootstrap --platform iOS --cache-builds<br>else<br>    echo &quot;All dependencies in sync&quot;<br>fi</pre><p>And VOILA! Just hitting <em>run</em> in Xcode will now make sure your Carthage build folder is kept in sync with your Cartfile.resolve file. So nobody will ever fail running your project because they forgot to update or download some dependencies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*_zJrJ4zM-gluQ-0iK0YAZA.gif" /></figure><p>Have a look at <a href="https://github.com/t-unit/Carthage-Auto-Checkout">Carthage-Auto-Checkout</a> for seeing the script in action.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3a064c0b2f3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ReSwift in Practice]]></title>
            <link>https://tobi-86596.medium.com/reswift-in-practice-1512e0f59eb5?source=rss-3733f959c7ce------2</link>
            <guid isPermaLink="false">https://medium.com/p/1512e0f59eb5</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[app-architecture]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[middleware]]></category>
            <category><![CDATA[reswift]]></category>
            <dc:creator><![CDATA[Tobias Ottenweller]]></dc:creator>
            <pubDate>Tue, 12 Jun 2018 06:37:09 GMT</pubDate>
            <atom:updated>2018-07-24T08:46:42.447Z</atom:updated>
            <content:encoded><![CDATA[<p>There is some buzz going around about using <a href="https://github.com/reactjs/redux">Redux</a>-Style application architecture for iOS apps. The pattern is definitely worth a closer look and has some big advantages, but how well does it work in practice?<br>Many introductions to ReSwift are already out there, however, I haven’t seen great examples of how to apply ReSwift in an actual shippable application.<br>In this article, I attempt to demonstrate how an almost “real-world” application can be build using ReSwift while keeping everything testable and integrated well with system APIs and network services.</p><h3>Introduction to ReSwift</h3><p>As mentioned, there is already an abundancy of information introducing ReSwift out there — I’m trying to keep it short.<br>A <em>unidirectional data flow</em> means not having your state of the app not kept in many different places. Instead, there is storage component keeping all state at a central location. Views react to changes of this state instead of handling it internally. <em>Actions</em> are the only way to trigger a state change. Actions don’t perform the state change by them self, rather think of them more like a message that signals that something shall change.. These “messages” are issued against a Store object which uses <em>Reducers</em> that perform the actual state change. There is also <em>Middleware </em>to handle side effect, which will get introduced later on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GIm2c8L0EyYcQZnGS9sSvw.png" /><figcaption>Data flow inside a ReSwift app: Actions are issued by a view. The <em>store</em> creates a new state object by supplying the current state and action to the reducer. The updated state is afterwards given (back) to the view.</figcaption></figure><p>Some big benefits to this approach:</p><ul><li>Business logic is kept separate from your UI</li><li>Reducers are <a href="https://en.wikipedia.org/wiki/Pure_function">pure-function</a> — great for testing</li><li>Simple logic inside the views — just react to state changes and send actions to the store</li><li>State can be easily shared between multiple views (or other components)</li><li>Overall much cleaner approach compared to standard MVC</li></ul><h3>Part 0: Getting Started</h3><p>There is a <a href="https://github.com/ReSwift/CounterExample">Counter-Example</a> that exposes the architecture described above in a very basic form. In the example, everything looks great and clean, but usual application development is a lot more complex. There are asynchronous operations (e.g. networking) and functionality provided by the OS or third-party frameworks that need to be integrated.</p><p>The rest of this article describes how to set up a fully tested (except UI) sample application integrating CoreLocation and a network service from Google that requires the user’s location. Here is a short list of requirements:</p><ul><li>Handle location permissions and changes to it.</li><li>Get the users locations and update on user movement.</li><li>Display restaurants nearby after receiving the user’s location.</li></ul><p>You can check out all the source code on <a href="https://github.com/t-unit/ReSwift-in-Practice">GitHub</a>. For each step there is at least one commit. Links to the corresponding source code will be provided for each step.</p><h4>Project Setup</h4><p>As a starting point, there is already an Xcode project with ReSwift as a dependency. Additionally, a simple network abstraction around the <a href="https://developers.google.com/places/web-service/search">Google Places API</a> with corresponding model classes for retrieving places (better restaurant) information is already there.</p><p>The first step towards displaying restaurants is setting up the required ReSwift objects: Store, Reducer and State.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/02e5d3a084a066e55adf9711f468b53a/href">https://medium.com/media/02e5d3a084a066e55adf9711f468b53a/href</a></iframe><p>The state is kept extremely basic for now. After places have been fetched successfully, the optional places object will hold them. During loading or error the value will be nil. This, of course, will be improved later on.</p><p>If you want to see the example in action or check all the details have a look at <a href="https://github.com/t-unit/ReSwift-in-Practice/tree/052c85bb39f13e4b01a864714ebbda04a1a16fb0">this commit</a>.</p><h3>Part 1: Networking</h3><p>The first step towards displaying restatuants to the user is performing a network request. Fake coordinates will be used for now since fetching the users geo-location will be handled later. Fetching takes place on viewDidAppear in the responsible ViewController. In ReSwift speak, this means <em>dispatching</em> a <em>fetch places</em> action.</p><p>Actions are defined as an empty protocol. Any type can just conform to it and act as an Action. So the following would work:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a9c46e0bedcc23920baba75dc0338314/href">https://medium.com/media/a9c46e0bedcc23920baba75dc0338314/href</a></iframe><p>This is nice but won’t actually perform a network request. Thankfully there is another way to define/dispatch an action. The store object allows supplying an action by passing a function (or closure) that returns an optional action. Those functions are called <strong>action creators</strong>. Here is the code snippet for it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/17b4bca880774812402531f04cbbddf1/href">https://medium.com/media/17b4bca880774812402531f04cbbddf1/href</a></iframe><p>Here, the fetchPlaces function can be dispatched using the store that will internally perform the network request to fetch places. Since this happens asynchronously nil (no action at all) is returned. Once the network request finishes successfully, another action is dispatched for updating the store with the received places.</p><p>This works just fine and you can find many examples that do networking in ReSwift applications like this, but this approach has a major issue:</p><p>As described earlier, an action should be viewed as a message that triggers a state change performed by a reducer. This is not the case here anymore. Instead, the action itself performs a network call as a side effect and dispatches another action on the response of the network call. The action executes now as a part of the business logic instead of being just a piece of information.</p><p>Also, note that testing such an action is not as simple as it could be. There is no easy way to inject/replace the network service while testing.</p><p>If you want to see the snippet above in action, have a look at <a href="https://github.com/t-unit/ReSwift-in-Practice/tree/f7b6cf9ae4049723873db7be889ee22065fbefaf">this commit</a>. There is also a simple table view displaying the data when the state is updated.</p><h4>Middleware To The Rescue</h4><p>How to actually do <em>proper</em> asynchronous operations based on actions is not really defined in ReSwift — for example, read this <a href="https://github.com/ReSwift/ReSwift/issues/214">thread</a>. There are multiple ways to do so. This article will show you an approach using middleware which is especially nice since it separates the UI or action dispatching parts of your application completely from the parts performing network operations.</p><blockquote>I found this <a href="https://github.com/timojaask/ReSwiftAsyncMiddlewarePattern">Example</a> to be a great inspiration for this approach.</blockquote><p>In ReSwift, middleware is just a function that is executed by the store before the reducer is hit. It is not allowed to alter the state, but can execute asynchronously while changing the current action or dispatch additional actions. Also, note that you can have multiple middleware functions. Common use cases for middleware are logging, caching and networking.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ViU1JHoEKqwN_hu15xZO4Q.png" /><figcaption>Information flow from dispatching an action to an updated state.</figcaption></figure><p>Middleware is defined as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9858950f057fa28d02c8b5fab452a730/href">https://medium.com/media/9858950f057fa28d02c8b5fab452a730/href</a></iframe><p>A middleware function gets supplied with a dispatch function for emitting additional actions and a closure that will return the current state. The middleware function is responsible for returning a DispatchFunction having another DispatchFunction as a parameter. So a function within a function. While the actual middleware code will live inside the nested function, the DispatchFunction supplied as a parameter is signaled with an action once the middleware is done.</p><p>Here is an example that just logs the action dispatched to the console that hopefully makes it easier to understand how middleware is working.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dd161a7024669e481d55967b55ffa7f2/href">https://medium.com/media/dd161a7024669e481d55967b55ffa7f2/href</a></iframe><blockquote>I’m not sure why the API for middleware is defined that way — I think this is much more complicated than it should be. I hope there will be a better way to declare middleware in the future. (There is a <a href="https://github.com/ReSwift/ReSwift/pull/188">PR</a> open for improving middleware. Hope it will change things for the better.)</blockquote><p>Moving forward in this application there is a little wrapper making it somewhat easier to create middleware. (This is still far from being a perfect API for declaring middleware. But it makes defining middleware, somewhat more convenient in the scope of the sample application.)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/33a94ea1d19d07e1be52afcf1270c556/href">https://medium.com/media/33a94ea1d19d07e1be52afcf1270c556/href</a></iframe><p>Have a look <a href="https://github.com/t-unit/ReSwift-in-Practice/tree/9ecfb8cd2ace0f4df7aa7ccaa22a5dd9f7256765">here</a> to see how I implemented this and how MiddlewareContext can be used.</p><h4>Using Middleware for Networking</h4><p>Instead of calling a network service directly in the action, a fetch places action will be dispatched by the view controller and intercepted by the middleware. The middleware now is responsible for performing networking as a side effect. The next paragraphs describe how network requests can be integrated using middleware.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yoGPPprgdtmSqkOLRVU36g.png" /><figcaption>Action flow when performing network calls inside a middleware.</figcaption></figure><p><strong>Update Actions</strong> — as you can see in the graphic above two actions are required now for fetching and setting places. (Setting here means updating the state.)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8cee392ccb40c70e54aefadbfb7c327b/href">https://medium.com/media/8cee392ccb40c70e54aefadbfb7c327b/href</a></iframe><p><strong>Write the middleware</strong> — the new middleware function should do something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ef80ac747d655fb97220d40c722ed79a/href">https://medium.com/media/ef80ac747d655fb97220d40c722ed79a/href</a></iframe><p>But this again would have the downside of not being able to test the code easily. There still is a way missing to inject the network service. Fortunately, middleware just needs to be created once at app start. So it is possible to write a function that will create our middleware using the dependency as a parameter.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8925f32a15792382b44ae0af7a15dcdf/href">https://medium.com/media/8925f32a15792382b44ae0af7a15dcdf/href</a></iframe><p>In the implementation, a PlacesServing is passed into the function. The function itself returns the actual middleware that can reference the <em>injected </em>dependency and perform the work. This looks like the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/65dabed7b9827082ae837ec36aa83dc6/href">https://medium.com/media/65dabed7b9827082ae837ec36aa83dc6/href</a></iframe><p>And this is how it is passed to the store:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8a2b4ff3b409667154a6c667bd309f50/href">https://medium.com/media/8a2b4ff3b409667154a6c667bd309f50/href</a></iframe><p>The main advantage here, of course, is that the middleware is now easily testable. Also, the definition and the dispatching of actions is now completely separate from the logic responsible for executing the network request.</p><p>Have a look at commit <a href="https://github.com/t-unit/ReSwift-in-Practice/tree/f97e4a76bcf359eb4e79f1e3c97db264913a12ec">f97e4a7</a> if you want to see this implication and the related tests in action.</p><h4>Clean Project Setup and State Improvements</h4><p>There are still a few unsound pieces in the app that should get cleaned up before moving on to integrating a system provided service into the app.</p><p>Currently, the app store is defined as a global variable in AppStore.swift. This is a code smell since it makes it easy to just reference the global variable in some piece of the code without thinking about dependency injection or reusability when things get moved around at a later state of the project.</p><p>One possible solution, shown here, is to set up the appStore inside the AppDelegate. This works great as long as the setup code is kept small. (A different solution should be found if there is a lot of setup code.) From now on the AppStore file has just a single line for the typealias of AppState while the AppDelegate now looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc94fae018c5ebb4b02811b657290be5/href">https://medium.com/media/fc94fae018c5ebb4b02811b657290be5/href</a></iframe><p>The only thing left is to now inject the now private appStore into the view controller:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b12bafe160db66ce002a29f82dba41c/href">https://medium.com/media/2b12bafe160db66ce002a29f82dba41c/href</a></iframe><h4>Loading State for Places</h4><p>So far, the app state just has an optional PlacesSearchResult, but what if the UI should display some sort of loading indication or an error when fetching restaurants failed? The solution is sort of simple, but requires some changes in the existing code. For each state, there is a case of an enum called Loadable:</p><ul><li>initial indicating that no loading ever took place</li><li>loading</li><li>value</li><li>error</li></ul><p>You can find the full changes in commit <a href="https://github.com/t-unit/ReSwift-in-Practice/tree/70d31f444dd3bb97a35b1636267281ee0729603d">70d31f4</a>. Here are the most important parts:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f0f8307b36ef38756e5d1ad1aace5118/href">https://medium.com/media/f0f8307b36ef38756e5d1ad1aace5118/href</a></iframe><p>This concludes the work on adding networking to this application. When using the application now you should be able to already see some restaurants at the “fake” user location.</p><h3>Part 3: CoreLocation</h3><p>After having working network operations and a well working ReSwift setup ,it is time to start looking into integrating a system service — CoreLocation — into the sample application.</p><h4>Keeping Track of State</h4><p>Let’s get started by looking into how authorization state and the current user location can be represented by the app state. There is a need for an object that retrieves data from CoreLocation (CLLocationManager) and emits actions. For the lack of a better name, LocationEmitter will be used for this object. Two more actions are also required: one for setting the new location and one for updating the authorization state. Writing the code for this is relatively straightforward. Here is a snippet for it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0956513693dc0fafc596131aa8eaeaac/href">https://medium.com/media/0956513693dc0fafc596131aa8eaeaac/href</a></iframe><p>The LocationEmitter gets a store and location manager object injected in the initializer so that the object is easy to test. The emitter must stay the delegate of the location manager and must be kept alive through the whole lifecycle of the app so that it can update the store when delegate calls are triggered. For these reasons the emitter is stored and set up in the app delegate:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea818fd106c5e2864211b92723e3220c/href">https://medium.com/media/ea818fd106c5e2864211b92723e3220c/href</a></iframe><p>Again, omitted are the changes required to the app state, reducers and tests here. If you want to dig into the details have a look at <a href="https://github.com/t-unit/ReSwift-in-Practice/tree/c9897e6dd2c5c525e52cd25565af00ae7c5a2149">this commit</a>.</p><h4>User Opt-In and UI</h4><p>Instead of requesting user permission for accessing GPS at app start, this app should ask the user at a more convenient time maybe after explaining why the app needs the user’s location. The UI will “simulate” this by presenting a button on the main UI when a user has not yet given permission. There will also be an error view when the user denied the permission request. Both views are shown and hidden depending on the authorizationStatus of the app state.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fdd891ae4d6cd4d6e3946df891e1c894/href">https://medium.com/media/fdd891ae4d6cd4d6e3946df891e1c894/href</a></iframe><p>To request authorization, the corresponding method of CLLocationManagercould be just called inside the IBAction of the button. However this would not be a good approach since the UI should not perform such a side effect. Just like before with networking, a good place for this is middleware where the view can just dispatch another action.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/343963ff21f780fc03cc9673546dd6b2/href">https://medium.com/media/343963ff21f780fc03cc9673546dd6b2/href</a></iframe><p>Again, like before, there is a <a href="https://github.com/t-unit/ReSwift-in-Practice/tree/c059b67d48beba6dcbd6c2a12e4a47be00178eb0">commit</a> with all the changes and test.</p><h4>Fetch Places based on Significant Location Change</h4><p>Now is the time to put everything together. The first step is to call startMonitoringSignificantLocationChanges on CLLocationManageronce the user granted permissions or when the app becomes active. This should also be a side effect, so another middleware is the best solution here. A new action must also be dispatched inside the AppDelegate.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/955e624e47bc58be69f1e65475a29123/href">https://medium.com/media/955e624e47bc58be69f1e65475a29123/href</a></iframe><p>Note that the information about the application becoming active will be completely ignored by the reducer. In addition to starting significant location updates, there is also a call to request the current location since Core Location will only call the delegate method once the user moved.</p><p>Last, but not least, the app should fetch new places once the user location changes. The action for this already exists and is currently dispatched inside viewDidAppear of the view controller. That must go away. Instead, the fetch places action has to be dispatched once the application state has a new location object set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0IswAA-RCtAZ0NuULbDnNg.png" /><figcaption>Diagram showing the data/information flow from receiving a new location until fetching places.</figcaption></figure><p>Unlike before, no side effects need to be executed and therefore no middleware is required. Instead, a Location Observer is required. On the outside, it behaves almost like some UI component, but instead of sending actions based on user input, it sends actions when the state has a specific change.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3eb83e1888e0aa8ccd158ea928676d54/href">https://medium.com/media/3eb83e1888e0aa8ccd158ea928676d54/href</a></iframe><p>The snippet above shows the implementation of observing location changes. Again integration and tests are omitted here. You can see the full implementation here: <a href="https://github.com/t-unit/ReSwift-in-Practice/tree/65bef0d6cafef067932013ee0938938f6dd65ac8">65bef0d</a></p><p>This finishes the work at the sample application. You should be able to build and run the application. After granting location permission, you should be able to see restaurants around you and while moving those should update automatically.</p><h3>Conclusion</h3><p>In this article I went further into details of writing an application with ReSwift than most other articles out there. When handling side effects I showed the heavy use of middleware. This goes somewhat against the sample projects provided (e.g. <a href="https://github.com/ReSwift/GitHubBrowserExample">GitHubBrowserExample</a>), but separates actions and network logic and improves testability.</p><p>The good news is that ReSwift is flexible enough to allow adjusting app architecture to fit your needs. On the other hand, I’m not very happy that the <em>standard</em> patterns don’t separate side effects from actions and don’t provide a good strategy testing. Also, a bit more guidance and introduction from project side would be useful.</p><p>As a non-Javascript developer that never used Redux, some API also does not feel right, particularly the middleware API could be improved.</p><p>It tried showing as much as possible of actual app development, but still there is much left uncovered. Big things like routing, good integration with UIKit classes (UITableView, UICollectionView, …), splitting up big applications into modules and making the presentation layer independent of system and external APIs, are missing in the example.</p><p>Anyway, I hope I showed some useful patterns in the article. If you liked what you have seen here, please also have a look at the <a href="https://github.com/t-unit/ReSwift-in-Practice">source code</a>. Overall, I think the sample app exposes a pretty sound architecture for a small to medium sized application especially, with a high test-coverage of 80%.</p><p>Thank you for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1512e0f59eb5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>