<?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 Richard Shepherd on Medium]]></title>
        <description><![CDATA[Stories by Richard Shepherd on Medium]]></description>
        <link>https://medium.com/@eggzotic?source=rss-63d3daebb8fa------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*4AyWYlqkrxwVWSei.jpg</url>
            <title>Stories by Richard Shepherd on Medium</title>
            <link>https://medium.com/@eggzotic?source=rss-63d3daebb8fa------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 12:18:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@eggzotic/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[Story Points]]></title>
            <link>https://medium.com/@eggzotic/story-points-46e8a4e586b7?source=rss-63d3daebb8fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/46e8a4e586b7</guid>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[firestore]]></category>
            <category><![CDATA[planning-poker]]></category>
            <category><![CDATA[story-points]]></category>
            <category><![CDATA[agile-planning]]></category>
            <dc:creator><![CDATA[Richard Shepherd]]></dc:creator>
            <pubDate>Mon, 05 Feb 2024 12:05:40 GMT</pubDate>
            <atom:updated>2024-02-05T12:05:40.754Z</atom:updated>
            <content:encoded><![CDATA[<p>Agile development teams may use tools such as Jira for storing, organizing and tracking their project planning artifacts — Epics, SubEpics, Stories, Tasks, Bugs, … One of the activities that is key to sprint-planning is reaching consensus on Story Points estimates — often used as a measure of story-complexity, or how-much-effort is required to complete each story or task.</p><p>In Jira, you might be familiar with this screen-snippet:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*By14F0yzb9Jo5_GdVJ6ghw.png" /><figcaption>Snippet from Jira Story</figcaption></figure><p>That Story Points field — how to (meaningfully) populate it?</p><p>In this post-COVID era, it is now more common for development teams to be working remotely, and meeting to discuss planning &amp; progress via tools such as Zoom, Google Meet, a Slack Huddle, MS Teams etc. While good old fashioned methods such as counting to 3 and agreeing for each person to then reveal their estimate on the current story via a show of fingers, should never be discarded, there are now more sophisticated methods.</p><p>A quick Google search will come up with a variety of publicly available apps. However our experience with using some of these typically ended with either:</p><ul><li>a limited number of “free uses” before some type of subscription commitment was required</li><li>a lack of context — the tool did not include the ability to enter the project name, and under each project to group stories, or the voting results (including individual votes) of each story</li><li>advertisments — yeah they’re not necessarily evil — but sure can be over-the-top in-your-face, which is detracting</li><li>desktop only — they may not be mobile browser-friendly</li></ul><h3><strong>A New Way</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RrM_uxJPAZeF7m9cJUHe4w.png" /></figure><p>One new option, which does not have any of the above drawbacks, is the <a href="https://story.points.rocks/">Story Points</a> app at <a href="https://story.points.rocks./">https://story.points.rocks.</a> Full disclosure: I designed &amp; developed this PWA. This is a totally free and secure app that allows teams of remote devs to organise their “Projects” (think Epics or SubEpics), Stories, and carry out online voting sessions to estimate for each story. It can also be used if you’re all in the office because, hey, who has time to get up and talk face-to-face or walk all the way to a meeting room now?! Remote work can be the introvert’s nirvana…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ITYfvxHVa7gyf3lFSOEkuA.png" /></figure><p>Story Points:</p><ul><li>supports a choice between the Planning Poker and Fibonacci Series points systems (per project)</li><li>offers a selection of methods for the vote-reveal:</li></ul><ol><li>manual (the default) — meaning that someone in the team has to click the “Reveal” button to reveal each persons vote, along with the resulting mean value</li><li>automatically after the last person has submitted a vote</li><li>immediate — basically removing the initially secret ballot part of the vote</li></ol><p>Each story, and its latest voting results, can be stored indefinitely — and voting sessions can be re-run over and over. If you don’t want to keep each story separately (or generally enter too much project or story info — in case that feels like duplication of effort or having 2 “sources of truth”)— hey you can just have a single placeholder project &amp; story and use it over and over for voting for each real story — there’s no restrictions really on how you use it.</p><p>Additionally, team members may be marked as voters (the default) or non-voting (e.g. for a Project Manager) who may be participating-in / facilitating the gathering but not necessarily wanting to place a vote. This is useful when you also select the 2nd option above to indicate that all expected votes have been submitted and the reveal can begin automatically.</p><p>Teams can literally be composed of any individuals. At present the only requirement is a Google-hosted account (e.g. any personal @gmail.com or any other business who’s identity-management-system (IMS) is hosted by Google — e.g. my current employer who is @nyriad.io). More options for authentication may be added in future — especially if user-feedback shows demand!</p><p>Cross organizational groups my be formed (e.g. a mix of accounts with different domains). The app includes a method to invite collaborators to your project, and even directly to a specific story (although membership still applies at the project-level — but it can be an added convenience to be taken directly to a story). All team members are equal — it’s primarily aimed at <em>willing</em> collaborators. Anyone can invite anyone else — and can also eject anyone from the team.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*amFUaxSSbJBcMUVKftV-Vg.png" /></figure><p>Overall, if you’re already familiar with the Story Points estimate system in some form, then this app should seem intuitive to use. But I am aware that each organization tends to have their own slant on Agile, and which parts they are fastidious about vs those they’re more relaxed about.</p><p>The app is adaptive to your screen size and proportions — meaning the experience should be pleasant on both desktop and mobile browsers. So, if this feels like it might fill a need in your software dev team — do try it out!</p><h3><strong>Demo Video</strong></h3><p>For those who prefer to learn via watching an instructional video — here’s a link to a YouTube intro and tutorial: <a href="https://youtu.be/VF_tfZKUftQ">https://youtu.be/VF_tfZKUftQ</a></p><h3><strong>Under the Covers</strong></h3><p>So what does the app consist of?</p><ul><li>The app is written in Flutter (see <a href="https://flutter.dev/">flutter.dev</a>).</li><li>State management is via ChangeNotifierProvider</li><li>Projects, stories and votes are stored in Google Firestore, with access controls that match each project’s membership</li><li>Authentication is Firebase Auth, and is delegated to Google-accounts (for now — more providers may be added in future).</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46e8a4e586b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[New Flutter App — the Developers What, How, Why?]]></title>
            <link>https://medium.com/@eggzotic/new-flutter-app-the-developers-what-how-why-7087a8a021c2?source=rss-63d3daebb8fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/7087a8a021c2</guid>
            <category><![CDATA[firestore]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[word-game]]></category>
            <category><![CDATA[provider]]></category>
            <category><![CDATA[tikka]]></category>
            <dc:creator><![CDATA[Richard Shepherd]]></dc:creator>
            <pubDate>Wed, 15 Jun 2022 11:40:59 GMT</pubDate>
            <atom:updated>2022-06-15T11:40:59.885Z</atom:updated>
            <content:encoded><![CDATA[<h3>New Flutter App — the Developers What, How, Why?</h3><p>As a solo hobbyist App-creator and Flutter enthusiast, it is a relatively rare occasion when I get so far as releasing to the AppStore &amp; PlayStore. So it feels like a significant milestone to reach when it does happen. Recently, both Apple and Google saw fit to publish my latest App “Tikka the Word Game” which is accessible here, per your mobile platform of choice:</p><ul><li>App Store: <a href="https://apps.apple.com/app/tikka-the-word-game/id1625446554">https://apps.apple.com/app/tikka-the-word-game/id1625446554</a></li><li>Play Store: <a href="https://play.google.com/store/apps/details?id=software.eggzotic.tikka">https://play.google.com/store/apps/details?id=software.eggzotic.tikka</a></li></ul><p>Apart from the obvious self-serving motive of increasing awareness of the Tikka App (hey, I had to say it before someone else did!), which is a word-strategy/guessing-game, <em>this article discusses some of the design &amp; implementation choices</em> that went into it. These might just be interesting to others on a similar path, or who have gone ahead of me and made similar (or different &amp; better!) choices.</p><p>I won’t go over the UI, flow, or how-to-play the game of Tikka here — I really hope that is sufficiently intuitive to anyone who does take the time to install and open it. Oh, and there is an in-app description of how to play. To add some color, here is a “happy” screenshot…you too can achieve this state by simply solving a challenge (e.g. Daily Word, or any random Solitaire game):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1pN4TN76TOyBBN8_2xYiJw.png" /><figcaption>Game Completion View</figcaption></figure><h3>State Management</h3><p>Provider with ChangeNotifier — aka ChangeNotifierProvider, along with my custom data-model classes. I’ve used this combination more often than any other — and it feels intuitive and like it does not “get in the way” of the pure-classes that hold the real state. In some previous projects I have also used Provider + BLOC — and really have no issues with it either. Except — that I find ChangeNotifierProvider is (for me) just much quicker to re-acquaint myself with after longer pauses (e.g. between projects). And I don’t feel like I’m missing out on anything by using Provider + ChangeNotifier. Perhaps BLOC does encourage more discipline in the data-structures and separation of the layers…or maybe I just get too fast-n-loose when using ChangeNotifierProvider as it doesn’t feel like it’s slowing me down at all?</p><p>For a good couple of years (it feels like), I was obsessed with State Management in Flutter — what is the “right” way? Coming from the early days of Swift (pre-Swift UI), for creating iOS Apps, the main mechanism which Apple seemed to promote was the Singleton for pure state, and the delegate architecture for making UI elements react to state changes. For Flutter, there were choices, for sure — but which was the “right” one? The whole widget-tree concept of Flutter took a long time to sink-in to my head, I’ll be honest. Eventually the core Inherited Widget pattern did get in, and Provider made that easier and more powerful to use. Stateless widgets with their single class, less boiler-plate-code and, er, absence of state(!), also appealed hugely. So Provider + ChangeNotifier in tandem with Stateless Widgets just resonated for me. And here we are today… Thanks Remi Rousselet and the Flutter team for the whole Provider suite!</p><h3>Persistent Storage</h3><p>Google Cloud Firestore. This is my first choice for persistent data storage. Even for Apps where no data-sharing is relevant, the ease of data-debugging that comes from having the data centralised, non-encoded, and off-device, always outweighs the initial convenience of using local-storage, for me. And it’s server-less (to the developer). The free tier includes ample reads &amp; writes per-day to allow no-cost development usage. And the predicted costs if the App’s user-base/activity really takes off? Well they’re (Google) not a charity after all…</p><p>Firestore is a NoSQL document-based database. It is schema-less, so your app code must either:</p><ol><li>be disciplined to write-what-you-expect-to-read (where your app is both the creator and consumer of the data), and/or</li><li>employ a no-trust approach to the data in any document (esp when something else creates it). Some would say “if you didn’t create the data, you can’t trust the data”.</li></ol><p>For this App, the first option above applies.</p><p>Especially to those coming from relational DBs, the schema-less feature of Firestore may sound like a lazy/cheap approach — pushing the data-integrity responsibility back onto the app-code (i.e. the client!) at runtime.</p><p>However all is not as it seems (yes, read on…).</p><p>Firestore uses “collections” (think “tables”) to group documents (think “records”). One of the high-value features of Firestore is the use of listeners — either listen for changes to a single document or to an entire collection. This last option allows the App to be responsive to changes in any document (or for document additions and removals) in the collection. Listeners should be used sparingly for any app that intends to scale out (think huge concurrent client-connection numbers), as there is a soft-limit of ~1 million concurrent listeners per DB. So, the ability to place arbitrary, multi-schema, documents in a single collection allows your App to react to changes in all the relevant data-structures with a single listener per App-instance. Yes, your code has to be equipped to de-serialize (think “constructor from JSON (almost)”) all the possible types of object that the listener may pickup from that single DB collection — but that is true regardless of how many places in the DB that contain these. Realising this alternate use-case for Firestore collections, seemed like a light-bulb moment.</p><p>Among other things, Firestore excels at:</p><ul><li>Large-scale concurrent usage where clients are mostly</li><li>writing to unique documents (or to documents in distinct collections), and/or</li><li>Reading from shared or unique documents</li></ul><p>The missing piece from the above is when you might wish to have multiple clients <em>writing to the same</em> central/shared document. There is a limit of ~1 write-per-second to a single document, which precludes this use-case. That makes aggregation tougher. e.g. updating some global stats directly from the clients. Practically though, that last use case ought to be controlled more centrally by an intermediate service. For those (like me) who want to remain server-less, Cloud functions is likely the best solution there. The costs of this, for likely use-cases, I’ve not calculated yet.</p><p>The centralised DB nature of Firestore makes it easy to implement features such as the Daily Word challenge in the Tikka App today. This was partially inspired by the popular Wordle game. Tikka offers it in all available word-lengths (from 4–9) to suit your appetite for challenge… Tikka, in its original form, was a 2-player game analogous to the popular Mastermind game (which was played with coloured pegs, instead of letters &amp; words). Future versions of Tikka will add in the player-vs-player option, and again Firestore will prove valuable as the player-interactions will be in-game and make use of the fact that all clients are accessing the same logical data-store-in-the-cloud. And both Apple and Google are moving away from their GameCenter-like offerings — pushing developers into building their own custom mechanisms for game-play-invitations and leaderboards.</p><h3>User Authentication &amp; Account Management</h3><p>Google Firebase Auth. Closely coupled with Cloud Firestore. If you’ve used Firestore before, you’ll be aware of all the options that come with it including Object Storage, and Cloud Functions. This App is likely to involve some Cloud Functions as the user-base grows — potentially for reporting and producing some aggregate stats — e.g. leaderboards. But Firebase Auth is the other major feature that is being used by Tikka today.</p><p>Anonymous accounts/logins also solve a challenge where storing users’ personally identifiable information is not desirable (or necessary), but keeping their app-specific-user-data separate is necessary. This App offers both options — an account keyed on the user’s email address, and anonymous auto-login style. The main advantage of signing up with your email address (today) is that the games and all your aggregated information (game-history, word-history, score-history) are accessible from any device where you login with that same account. And in future it will be required to participate in 2-player games. Anonymous accounts remain private to the specific device where you did auto-login. Oh, and finally, you can convert your anonymous account into a fully-fledged account any time, and then gain the advantages mentioned above for those. All of this is catered for in the standard feature set of Firebase Auth.</p><h3>UI Widget Set</h3><p>Primarily the Flutter builtin Material and Cupertino widgets, with a few community additions. I’m no visual artist — there’s no getting away from that! However, the familiarity of those oft-seen-before UI elements hopefully makes the user experience intuitive so you’re up-and-away playing in no time.</p><p>I highly recommend the Simple Animations module from Felix Blaschke.</p><p>The FlutterFireUI module is an easy way to quickly add user sign-in/registration and account-info screens. These complement the backend user-management features that Cloud Firestore provides. For me this was valuable and much appreciated to avoid the work of implementing these from scratch. For developers who’ve already designed their own screens for these functions, then all that work you’ve done may sway you towards keeping that as the branding and customisability of those will likely exceed what is possible with the FlutterFireUI widgets. That said, there is some basic branding support provided with FlutterFireUI. I found that the documentation is lagging a bit beyond what functionality is actually available — so don’t be put off purely by what you’ve read is possible — there is likely even more which you can discover via the builtin hints and docs available directly in your IDE (which is VS Code, for me).</p><h3>Key App Assets</h3><p>Being a word game, one of the early challenges for Tikka was finding a word-list with a good balance of completeness (e.g. including plurals) and correctness (e.g. excluding proper-nouns, abbreviations, …). During early testing, while using stand-in word-lists derived from the likes of the /usr/share/dict/words file on my Mac Laptop, the gaps in these 2 areas often distracted my tester (ok, yes, my wife) more than the UI that was the intended evaluation-target at the time. I searched high and low, and at last I discovered the great tool at <a href="http://app.aspell.net/create">http://app.aspell.net/create</a>. This includes a bunch of customisations that you can make around acceptable levels of spelling variations, and even a choice of English dialect options. Although, as of today, Tikka supports American English only — yes even though I am based in New Zealand where we (think we) speak the Queen’s English…(but, you know, largest audience and all…).</p><h3>And in Closing…</h3><p>So those are the major App developer topics that came to mind regarding this new App “Tikka the Word Game”. None of which matter to the end-user, of course. Maybe it was interesting to other developers though?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7087a8a021c2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter-ready Encryption Utility]]></title>
            <link>https://medium.com/@eggzotic/flutter-ready-encryption-utility-697aaed97012?source=rss-63d3daebb8fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/697aaed97012</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[credentials]]></category>
            <category><![CDATA[encryption]]></category>
            <dc:creator><![CDATA[Richard Shepherd]]></dc:creator>
            <pubDate>Mon, 23 Dec 2019 14:39:54 GMT</pubDate>
            <atom:updated>2019-12-24T06:51:21.716Z</atom:updated>
            <content:encoded><![CDATA[<h4>Secure my Secrets</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v_P9mOROsdT2ZMxt6SJPQw.png" /></figure><h3>What?</h3><p>In my previous articles we’ve journeyed from the vanilla Flutter starter App, through <a href="https://medium.com/@eggzotic/stateless-flutter-2e14b6ae30b5">separating the state</a>, making it <a href="https://medium.com/@eggzotic/local-data-persistence-in-flutter-7f82c54efe5">persistent via local-storage</a>, and then via <a href="https://medium.com/@eggzotic/cloud-based-data-persistence-in-flutter-5fd7f1440f25">Cloud Storage with Google Firestore</a>. The eventual next step in that progression will be adding authenticated database access. However in this article we’ll take a slight digression to create an assistant utility for later use relating to the process of authentication.</p><h3>Why?</h3><p>Have you ever needed to use an API key for a 3rd party network data service, or some static/preset credentials, in a Flutter app? Especially in a situation where the end-user is not required to first personally sign-in to the App before said API service (or backend-login) is called on? This generally raises two challenges:</p><ul><li>how or where to store those sensitive values (at compile time), to avoid unwanted disclosure?</li><li>how to access or fetch those values (at runtime), to enable accessing information from a remote source?</li></ul><h3>How?</h3><p>A standard way to protect sensitive data is with encryption. For Flutter, a handy encryption library is <a href="https://pub.dev/packages/encrypt">Encrypt</a>. 2-way encryption is supported, so we can pre-encrypt the values (e.g. an API key or static username/password) prior to compilation — meaning we don’t have those sensitive strings exposed in plain-text in the source code or in the subsequent app-bundle that is installed on end-user devices. At runtime we can access the encrypted values and decrypt them just before making that API call or submitting a sign-in operation. For added obscurity and manageability, we can store the encrypted values outside of the code — either locally in an asset-file or remotely in a database — fetching them at runtime. In that last case it means that we, the developer, can update the values as necessary without requiring an app-update and all the release-related overhead.</p><p>For the task of the pre-encryption we can create a handy 2-way encryption command-line utility in Dart using the very same <a href="https://pub.dev/packages/encrypt">Encrypt library</a> as we can use within our Flutter app code.</p><p>The utility code and usage instructions are in the <a href="https://github.com/eggzotic/simple_cryption">GitHub repo</a>.</p><p>We’ll go over the code, show some simple usage examples, and how we can use the resulting encrypted strings in our Flutter App.</p><h3>But really, how?</h3><p>We’ll create a simple encrypt-and-decrypt command-line utility in Dart. This will not use the same Dart engine that is packaged with Flutter. Instead follow these <a href="https://dart.dev/get-dart">directions to install the standalone Dart SDK</a>.</p><p>Next, download the <a href="https://github.com/eggzotic/simple_cryption">simple_cryption repo</a>. As per the README.md, you need to run pub get once to pull down the dart packages mentioned in the dependencies of the pubspec.yaml — namely the <a href="https://pub.dev/packages/encrypt">Encrypt library</a> and the <a href="https://pub.dev/packages/args">Args package</a>.</p><p>The Dart code is all in the simple_cryption.dart file. It mostly consists of using the <a href="https://pub.dev/packages/args">Args package</a> to identify the flags and options, and whatever remains of the command-line will be treated as strings to be encrypted or decrypted. By default, if neither -e nor -d are specified, then the strings will be encrypted (as if -e was specified).</p><p>The usage options can be seen by running the utility without extra args:</p><pre>Usage: dart simple_cryption.dart [ -e | -d ] [ -k &lt;key&gt; ] &lt;string&gt; ...<br>-e, --encrypt    encrypt strings<br>                 (defaults to on)<br>-d, --decrypt    decrypt strings<br>-k, --key        use a non-default key (max 32 chars)</pre><p>Here’s an example, using the super-sensitive(!?) string “fun with flutter”:</p><pre>$ dart simple_cryption.dart -e &quot;fun with flutter&quot;<br>encrypt: fun with flutter --&gt; XfmMLkgvdd66xG/PIPNZkgFIYDKtjvGY+ynjd/hb5TA=</pre><pre>$ dart simple_cryption.dart -d XfmMLkgvdd66xG/PIPNZkgFIYDKtjvGY+ynjd/hb5TA=<br>decrypt: XfmMLkgvdd66xG/PIPNZkgFIYDKtjvGY+ynjd/hb5TA= --&gt; fun with flutter</pre><p>Or, using a non-default key:</p><pre>$ dart simple_cryption.dart -e -k &quot;encryption is the key&quot; &quot;fun with flutter&quot;<br>encrypt: fun with flutter --&gt; fUCCsVDLeBm2Jh/g0tIFfZ2929Avz8SP0c6sqAkFrFE=</pre><pre>$ dart simple_cryption.dart -d -k &quot;encryption is the key&quot; fUCCsVDLeBm2Jh/g0tIFfZ2929Avz8SP0c6sqAkFrFE=<br>decrypt: fUCCsVDLeBm2Jh/g0tIFfZ2929Avz8SP0c6sqAkFrFE= --&gt; fun with flutter</pre><p>So, we can encrypt text. And we can take an encrypted string and extract the original plain-text — so long as we know and use the same key for both operations.</p><p>To use a resulting encrypted value in our flutter app, we can extract the relevant code from simple_cryption.dart:</p><pre>import &#39;package:encrypt/encrypt.dart&#39;;<br>...<br>final sourceStrings = <em>&lt;list of encrypted strings&gt;</em>;<br>final rawKey = <em>&lt;the same 32-char-string used for encryption&gt;</em>;<br>...<br>final key = Key.fromUtf8(rawKey);<br>final iv = IV.fromLength(16);<br>final encrypter = Encrypter(AES(key));<br>...<br>sourceStrings.forEach((source) {<br>  final decrypted = encrypter.decrypt64(source, iv: iv);<br>  <em>&lt;use-or-assign the decrypted strings here&gt;</em>;<br>});</pre><p>Both sourceStrings and rawKey can have their values loaded from asset files (with source-control exclusion (e.g. .gitignore)), or a remote database, keeping them completely outside of your source-code.</p><p>Note that in a situation as described in the opening paragraph, encryption alone does not completely secure your sensitive access-strings. For more details see the <a href="https://medium.com/@sokrato/storing-your-secret-keys-in-flutter-c0b9af1c0f69">article about storing secrets in Flutter</a>.</p><p>In my next article we’ll see how to utilise this as part of protecting and managing static credentials for the next iteration of the Stateless Persistent-Data Flutter App (see the links below for the evolution so far).</p><p>Previous articles: <a href="https://medium.com/@eggzotic/cloud-based-data-persistence-in-flutter-5fd7f1440f25">Cloud-based Data Persistence in Flutter</a>, <a href="https://medium.com/@eggzotic/local-data-persistence-in-flutter-7f82c54efe5">Local Data Persistence in Flutter</a>, <a href="https://medium.com/@eggzotic/stateless-flutter-2e14b6ae30b5">Stateless Flutter</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=697aaed97012" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cloud-based Data Persistence in Flutter]]></title>
            <link>https://medium.com/swlh/cloud-based-data-persistence-in-flutter-5fd7f1440f25?source=rss-63d3daebb8fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/5fd7f1440f25</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[persistent-state]]></category>
            <category><![CDATA[firestore]]></category>
            <dc:creator><![CDATA[Richard Shepherd]]></dc:creator>
            <pubDate>Mon, 16 Dec 2019 03:58:34 GMT</pubDate>
            <atom:updated>2019-12-16T13:35:48.890Z</atom:updated>
            <content:encoded><![CDATA[<h4>Share my State</h4><p>Disclaimer: I am not affiliated with Google in any way other than being a general consumer of their free services (e.g. Gmail).</p><h3>What?</h3><p>In my <a href="https://medium.com/@eggzotic/local-data-persistence-in-flutter-7f82c54efe5">previous article</a> we augmented the <a href="https://medium.com/@eggzotic/stateless-flutter-2e14b6ae30b5">Stateless Flutter</a> starter app, by adding local persistent-storage to our state’s data via the SharedPreferences package.</p><p>Our Flutter starter app now has a single screen with a counter in the center of the screen. The counter begins at zero, and via a “+” button in the lower-right it increments, by one, at each tap. We also added a reset-to-zero button, for a little variety. Every time we re-start the app, the counter picks up where we left off last time…well it does if:</p><ul><li>we’re using the same device/simulator</li><li>we don’t uninstall the app from that device/simulator</li></ul><p>There’s a further list of caveats to consider listed at the end of the <a href="https://medium.com/@eggzotic/local-data-persistence-in-flutter-7f82c54efe5">previous article</a> that might be too limiting for your longer term app aspirations.</p><p>In this episode we’ll replace SharedPreferences by instead storing our state data in a Cloud-based database — specifically Google Cloud Firestore. We’ll demonstrate how this also gives us the ability to share data across multiple devices concurrently.</p><p>Here’s a peek at what our app will look like when we’re finished this article. To highlight the new shared-data capability, we demonstrate with both an iOS simulator and an Android Emulator running the same code, side-by-side. Each tap on the increment (or reset) button of one device is quickly reflected on both devices:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*7-mZo_TqPbzU-DPLvvL4vg.gif" /></figure><p>The GitHub repo for the finished product above is at <a href="https://github.com/eggzotic/flutter_persistent_cloud">https://github.com/eggzotic/flutter_persistent_cloud</a>. But don’t go there yet. As stated in the earlier episodes, the learning is in the journey we follow below. Besides that, if you take my repo as-is, it is missing the Google Firestore plist/JSON files — you need to create your own Firestore Project and DB so that you will have access to the console for the backend-setup, and the ability to add your own iOS and Android apps. So treat the repo as a reference for debugging your source code only.</p><h3>Why?</h3><p>Making data available beyond the lifetime of an app invocation, as we did in the last article, is just step one.</p><p>Storing small amounts of data directly on-device is handy for quick access and re-use — but it may not be scalable (or appreciated by the users!) as the volume of data grows. Trusting data-storage to each user’s device can be a risk. If an app’s data includes larger objects such as images or video then storing on-device may not be ideal. If the user’s device is lost or destroyed then their data will be gone with it.</p><p>Making data outlive even the installation of an app on a user-device may be desirable (or required). The aggregate data (i.e. the combined data from all your app users) of your app may need to be analysed, or stored centrally for some compliance requirement — this cannot be done if the data is individually stored on each user-device only.</p><p>Many apps enable a user to create data, and then make that data available for other users of the app to consume, e.g. can anyone say “Social Media”?</p><p>For this functionality we need to store data where it can easily be made available to all app-users, subject to suitable access-related logic.</p><h3>How?</h3><p>In this article, for no particular reason (other than the author’s familiarity with it) above other equivalent options, we’ll use “Google Cloud Firestore” to store our state data off-device. Firestore is a sophisticated product, but one I’ve found very useful for real world apps. Setup is more involved than on-device options, but the payback is that we also get to use more sophisticated features for enhanced functionality in our apps. Firestore is also free for small-to-medium scale projects.</p><p>No longer will we entrust the durability of our state data to the device on which it is created, and where its availability beyond that device is effectively nil.</p><h3>But really, how?</h3><p>As we did in the <a href="https://medium.com/@eggzotic/local-data-persistence-in-flutter-7f82c54efe5">previous article</a> we will use the finished product from there as our starting point. In case you don’t have it already, you can pull it from <a href="https://github.com/eggzotic/flutter_persistent_local">the repo</a>. Rename the top-level folder to our new project name: flutter_persistent_cloud.</p><h4>Clutter Cleanup</h4><p>Open the pubspec.yaml file and update the name and description lines at the top of the file. Once you have updated the name (e.g. to flutter_persistent_cloud), you may also need to update the test/widget_test.dart file where an import line will be broken due to the package name change. Then run this to sync up:</p><pre>flutter packages get</pre><p>Due to our re-using the finished result of previous projects as the starting-point for this project, there is some embedded config within our iOS and Android folders that is now a bit off. So we will take the sledgehammer approach and simply delete those folders entirely, and subsequently use flutter to recreate them. This demonstrates a handy feature of flutter that can be used if either of the build or platform folders (ios, android), ever become corrupted when you’re working on an app.</p><p>Simply remove those folders. e.g. On Linux or Mac OS you can do it like so:</p><pre>cd flutter_persistent_cloud<br>rm -rf ios android build</pre><p>Then re-create these with “fresh” versions:</p><pre>cd ..<br>flutter create flutter_persistent_cloud<br>cd flutter_persistent_cloud</pre><p>Note that in this situation, flutter create … will re-create the missing folders (ios, android, build) only rather than creating a completely new default project. It will not touch the existing contents of the lib/ folder (all our source code!) or pubspec.yaml file.</p><h4>Create the Firestore Project</h4><p>In your browser, open the <a href="https://console.firebase.google.com/">Firebase Console</a> and login to your Google account (if not done automatically). Here you should be greeted with “Your Firebase projects”. Click the link to create/add a new project. Follow the process of:</p><ol><li>Enter your project name: e.g. FlutterPersistentCloud</li><li>Disable Google Analytics for this project</li><li>Create Project</li><li>Wait while a new Firebase Project is provisioned.</li><li>Select “Continue” to return to your “Project Overview”</li><li>Various features to add are presented: select “Cloud Firestore”.</li><li>Under the “Cloud Firestore”, select “Create database”.</li><li>Accept the default, “Start in Production mode”</li><li>Select a “Cloud Firestore location” near you (or just accept the default)</li></ol><p>From the main database screen select “Start collection” to create an initial collection named “counterApp”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/668/1*WelcvymP2AG3IX6eDgmQtw.png" /></figure><p>For the first document, give it the name “shared”:</p><ul><li>Name the first field “counterValue”, of type “number” with value 0</li><li>Also add a field “deviceName”, of type “string”, with value “No device”</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*n1XRhKaZIe9brkkMf97M7g.png" /></figure><p>We now have our basic persistent data storage in the cloud all setup and initialised.</p><h4>Set the Database Access Rules</h4><p>For a fully fledged multi-user app Google Cloud Firestore provides full user-authentication management features. However, user-authentication is beyond the scope of this article. So to satisfy the requirements for our demo-app (and to safeguard our new Firestore database from possible abuse), we will simply limit access to the single document “shared”. There is a size-limit of 1 MB, and a limit of 20000 fields, per document with Cloud Firestore.</p><p>While we’re still in the “Database” section of our Project on the Firebase Console, select the “Rules” tab. Since we chose the (default) production mode, all access to the database is initially denied, as can be seen from the starting access-ruleset:</p><pre>rules_version = &#39;2&#39;;<br>service cloud.firestore {<br>  match /databases/{database}/documents {<br>    <em>match /{document=**} {<br>      allow read, write: if false;<br>    }</em><br>  }<br>}</pre><p>Update the rules, by adding the italicised lines below, just above that original match statement:</p><pre>rules_version = &#39;2&#39;;<br>service cloud.firestore {<br>  match /databases/{database}/documents {<br>    <em>match /counterApp/shared {<br>      allow read, write: if true;<br>    }<br>    </em>match /{document=**} {<br>      allow read, write: if false;<br>    }<br>  }<br>}</pre><p>Then select “Publish” to activate the new rules.</p><p>Be sure that the path (i.e. /counterApp/shared) in your new match statement above <em>matches</em> exactly the collection name and document names you created earlier — the path matching is case-sensitive.</p><p>These new rules allow anyone access to just that single document “shared” that we created earlier.</p><h4>Add a Mobile App to Firebase Project</h4><p>Time to add an Android and/or iOS app to the Firebase Project. For a production Flutter app it is likely you will want to add both mobile platforms. However, for a learning exercise like this, you might choose to focus on just the one most convenient for you. We’ll cover both cases here — pick whichever you prefer (or both!).</p><p>The primary <a href="https://firebase.google.com/docs/guides">documentation guides</a> for Firebase are targeted at native iOS and Android apps (along with Web, and others). <a href="https://firebase.google.com/docs/flutter/setup">Flutter instructions</a> are included in another part of the site. Below is a distilled set of steps that I have found to be reliable. We will use the <a href="https://pub.dev/packages/cloud_firestore">Cloud Firestore package</a>.</p><p>The instructions that follow are based on the “Setup”, for each mobile platform, at the <a href="https://pub.dev/packages/cloud_firestore">Cloud Firestore package</a> site along with a couple of tweaks that I have found to smooth the path for each mobile platform.</p><h4>To add an iOS App</h4><p>If you intend to run your app on Android-only — then skip this section.</p><p>In your Firebase Console, select “Project Overview”, then select the iOS icon above “Add an app to get started”.</p><p>We need to fill-in the iOS Bundle ID of our project. This can be extracted purely from the command-line, or from Xcode.</p><p>Method 1: At the Mac terminal, from the project top-level folder, copy and paste this command (as a single line):</p><pre>grep PRODUCT_BUNDLE_IDENTIFIER ios/Runner.xcodeproj/project.pbxproj | head -1 | awk &#39;{ print $3 }&#39; | cut -f1 -d &#39;;&#39;</pre><p>In my case the output to the above is: software.eggzotic.flutterPersistentCloud</p><p>Then copy and paste your output into the “iOS bundle ID” field at the “Register app” step in your browser.</p><p>Method 2: use the Xcode GUI to find the bundle ID. At the Mac terminal, from the project top-level folder run this to open Xcode in the correct folder:</p><pre>open ios/Runner.xcworkspace</pre><p>Select “Runner” in the top-left of the Project Navigator. In the “General” pane, at the “Identity” section copy the value in the “Bundle Identifier” field. Then paste this value into the “iOS bundle ID” field at the “Register app” step in your browser.</p><p>Regardless of which method you used above, continue here: Ignore the optional “App nickname” and “App Store ID” fields. Click “Register app”.</p><p>Click the button/link “Download GoogleService-Info.plist”. This file will now appear in your browser Downloads folder. Locate the file and, if necessary, rename it to exactly “GoogleService-Info.plist”. E.g. if you already had a file by that name present, the new one may have an added “ (1)” in the name — which needs to be corrected.</p><p>If Xcode is not already opened, open it as above for finding the Bundle ID. Drag and drop this GoogleService-Info.plist into the Runner folder of Xcode’s Project Navigator, right above Main.storyboard. Accept the defaults of the Xcode confirmation dialog. We can quit Xcode at this point — never needing to return!</p><p>Note that this is where we stop following the steps on the Firebase Console site. We do <em>not</em> follow the “Add Firebase SDK” and subsequent steps that would be done for a pure native iOS App. Flutter takes over from here. Just select the big “X” in the top-left of the web-page to return to the “Project Overview” screen.</p><h4>To add an Android App</h4><p>If you intend to run your app on iOS-only — then skip this section.</p><p>From your “Project Overview”, select the Android icon above “Add an app to get started” — or select “Add app” and then the Android icon if you’ve already added an iOS app.</p><p>We need to fill-in the Android package name of our project. This can be extracted purely from the command-line, or from Android Studio. Personally, I find the command-line method more straight forward here — having never become very familiar with Android Studio. I’ll leave the Android Studio method as an exercise for the reader — although it is most likely the more practical option for Windows Users.</p><p>On Linux or Mac copy-n-paste the below command into the terminal (as a single line):</p><pre>grep -i applicationID android/app/build.gradle | awk &#39;{ print $2 }&#39; | cut -f2 -d\&quot;</pre><p>In my case, the output to the above is:</p><pre>software.eggzotic.flutter_persistent_cloud</pre><p>Then copy and paste your output into the “Android package name” field at the “Register app” step in your browser.</p><p>Ignore the optional “App nickname” and “Debug signing certificate SHA-1” fields. Click “Register app”.</p><p>Click the button/link “Download google-services.json”. This file will now appear in your browser Downloads folder. Locate the file and, if necessary, rename it to exactly “google-services.json”. E.g. if you already had a file by that name present, the new one may have an added “ (1)” in the name — which needs to be corrected.</p><p>Move the file from your Downloads folder into the android/app folder of your flutter project.</p><p>Edit the file android/build.gradle — find the buildscript section and check that the repositories subsection contains the line:</p><pre>google()</pre><p>Also check that the allprojects section, repositories subsection, includes the line:</p><pre>google()</pre><p>In the buildscript section, add this line to the dependencies subsection:</p><pre>classpath &#39;com.google.gms:google-services:4.3.3&#39;  // Google Services</pre><p>Edit the file android/app/build.gradle. Find the line:</p><pre>apply plugin: &#39;com.android.application&#39;</pre><p>and below it add this single line:</p><pre>apply plugin: &#39;com.google.gms.google-services&#39;  // Google Play services</pre><p>Note that this is where we stop following the steps on the Firebase Console site. We do <em>not</em> follow the “Add Firebase SDK” and subsequent steps that would be done for a pure native Android App. Flutter takes over from here. Just select the big “X” in the top-left of the web-page to return to the “Project Overview” screen.</p><p>Extra required step for Android — we need to update the file android/app/build.gradle and change this line:</p><pre>minSdkVersion 16</pre><p>to instead be:</p><pre>minSdkVersion 21</pre><p>for compatibility with the Google Cloud Firestore package during build. This effectively excludes some older versions of Android, but this should not be a real problem for modern devices.</p><h4>All Platforms</h4><p>Now that we have made the platform-specific mods to accommodate our mobile-platform(s) of choice, we can begin work on the Flutter project.</p><p>Add these lines to our pubspec.yaml file in the dependencies section:</p><pre>cloud_firestore: ^0.12.11<br>device_info: ^0.4.1+3</pre><p>and remove/comment-out the line referring to shared_preferences. Then run</p><pre>flutter packages get</pre><p>To the code changes! We will introduce a new class to enable extracting our device name. Create the file lib/my_device.dart and add this content:</p><pre>import &#39;dart:io&#39;;<br>import &#39;package:device_info/device_info.dart&#39;;<br>import &#39;package:flutter/material.dart&#39;;</pre><pre>// helper class to get my device name<br>class MyDevice with ChangeNotifier {<br>  // Constructor<br>  MyDevice() {<br>    _setup();<br>  }<br>  //<br>  // instance properties<br>  String _name;<br>  String get name =&gt; _name;<br>  //<br>  // transient properties<br>  bool _isWaiting = true;<br>  bool get isWaiting =&gt; _isWaiting;<br>  //<br>  void _setup() async {<br>    final devInfo = DeviceInfoPlugin();<br>    if (Platform.isAndroid) {<br>      final androidInfo = await devInfo.androidInfo;<br>      _name = androidInfo.host;<br>    } else if (Platform.isIOS) {<br>      final iosInfo = await devInfo.iosInfo;<br>      _name = iosInfo.name;<br>    } else {<br>      _name = &#39;Other&#39;;<br>    }<br>    _isWaiting = false;<br>    notifyListeners();<br>  }<br>}</pre><p>Notice that second line import — we’re using the <a href="https://pub.dev/packages/device_info/versions/0.4.1+3">DeviceInfo package</a> which provides the friendly device-name. We’ll use that information to record the device which last updated the counter. Since our new project will be sharing the data with all other devices running the app, it will give each user a little insight as to who made the most recent update. This is a compromise between not giving away too much personally-identifiable data, while still helping to highlight how we’re sharing data across devices.</p><p>Note that in this case we’re deliberately using not-the-latest-version of DeviceInfo, so as to be compatible with Flutter 1.9. If you’re using Flutter 1.10+ already then you should be good to use the very latest version.</p><p>The import for dart.io is required to give us access to the Platform class, which helps us identify which platform we’re on at runtime.</p><p>Finally, notice that we use ChangeNotifier with our new class MyDevice since it involves async operations and we need to notify our listeners when the device name has been set. Again we use a transient state property _isWaiting (with an accompanying public getter) to indicate whether the instance is ready.</p><p>Coming back to lib/counter_state.dart, remove the import for shared_preferences. Add these imports, in its place:</p><pre>import &#39;package:cloud_firestore/cloud_firestore.dart&#39;;<br>import &#39;my_device.dart&#39;;</pre><p>Remove the shared-prefs key static property we had before:</p><pre>static const _sharedPrefsKey = &#39;counterState&#39;;</pre><p>and replace it with these lines which will provide us the location in the database of the data-document as well as the field names under which our data is stored:</p><pre>// the location of the document containing our state data<br>final _sharedCounterDoc = Firestore.instance.collection(&#39;counterApp&#39;).document(&#39;shared&#39;);<br>// convenience, to avoid using these string-literals more than once<br>static const _dbCounterValueField = &#39;counterValue&#39;;<br>static const _dbDeviceNameField = &#39;deviceName&#39;;</pre><p>Again, note that the string literals above must match exactly the collection and document names we created in Firestore and set in the DB access rules. Any mismatches among those three (DB structure, DB access-rules and code) will result in the app failing to function correctly).</p><p>Find the declaration of _value:</p><pre>int _value;</pre><p>and add these lines below it, to store the info relating to the device which last updated the counter, as well as our own device name:</p><pre>String _lastUpdatedByDevice;<br>MyDevice _myDevice;</pre><p>Below the getter for value, add these new getters so we can access the name of the last device to update the counter as well as our own device name from the UI:</p><pre>String get lastUpdatedByDevice =&gt; _lastUpdatedByDevice;<br>String get myDevice =&gt; _myDevice.name;</pre><p>Also, find the definition of the getter isWaiting:</p><pre>bool get isWaiting =&gt; _isWaiting;</pre><p>and update it to take into account whether _myDevice is ready:</p><pre>bool get isWaiting =&gt; _isWaiting || _myDevice.isWaiting;</pre><p>We will completely separate the operations of “save” and “load”. We can delete the current definitions of _save() and _load():</p><pre>void _load() =&gt; _store(load: true);<br>void _save() =&gt; _store();</pre><p>Our previous _store() will be used for save only. So rename it to _save().</p><p>We’ll update the _save() method like so:</p><ul><li>The optional load boolean can be removed from the parameter list — we’ll no longer use that.</li><li>We can remove the artificial delays (i.e. Future.delayed) because we will be interacting with a real network call out to Google Cloud Firestore.</li><li>The content of the try clause will become a single call to DocumentReference.setData with a Map literal containing both the counter value (_value) and our device-name (_myDeviceName)</li></ul><p>So our _save() method will be as below. If you put it side-by-side with the original _store() that we started out with, hopefully the similarity will be clear.</p><pre>//  save the updated _value to the DB<br>void _save() async {<br>  _hasError = false;<br>  _isWaiting = true;<br>  notifyListeners();<br>  try {<br>    await _sharedCounterDoc.setData({<br>      _dbCounterValueField: _value,<br>      _dbDeviceNameField: myDevice,<br>    });<br>    _hasError = false;<br>  } catch (error) {<br>    _hasError = true;<br>  }<br>  _isWaiting = false;<br>  notifyListeners();<br>}</pre><p>For loading/receiving data we will use a feature of Firestore that enables us to receive updates whenever there are changes in the content (or even existence) of a document. This method is DocumentReference.snapshots() and it returns a Stream of DocumentSnapshot objects. Since we have a stream, we can use the standard method of adding a Stream listener to define actions to be performed every time updates are received. Each time the document is updated then all currently listening devices will receive new data in the form of a DocumentSnapshot object which encapsulates the current state of the document and some metadata such as the document ID, whether the data came from local-cache (more on that later), and whether the data even exists!</p><p>We’ll call this method _listenForUpdates() and here it is:</p><pre>// how we receive data from the DB, and notify<br>void _listenForUpdates() {<br>  // listen to the stream of updates (e.g. due to other devices)<br>  _sharedCounterDoc.snapshots().listen(<br>    (snapshot) {<br>      _isWaiting = false;<br>      if (!snapshot.exists) {<br>        _hasError = true;<br>        notifyListeners();<br>        return;<br>      }<br>      _hasError = false;<br>      // Don&#39;t trust what we receive<br>      // - convert to string, then try to extract a number<br>      final counterText = (snapshot.data[_dbCounterValueField] ?? 0).toString();<br>      // last resort is use 0<br>      _value = int.tryParse(counterText) ?? 0;<br>      _lastUpdatedByDevice = (snapshot.data[_dbDeviceNameField] ?? &#39;No device&#39;).toString();<br>      notifyListeners();<br>    },<br>    onError: (error) {<br>      _hasError = true;<br>      notifyListeners();<br>    },<br>  );<br>}</pre><ul><li>The block of code inside .listen(…) is executed every time an update is received from Firestore — regardless of who changed the data. The updatedDocumentSnapshot object (called snapshot, here) is passed to the block and processed, with all conclusions resulting in notifyListeners() being called to notify the UI.</li><li>In the above you can see we begin the actions by declaring that we’re no longer waiting — all of these actions are synchronous after all.</li><li>We check that there is some data (snapshot.exists is true) otherwise we notify that an error has occurred and return from this update.</li><li>we then extract the new values for _value and _lastUpdatedByDevice from the Map that is contained in snapshot.data.</li><li>note that there is currently a quirk (or bug?) with the CloudFirestore packages where DocumentReference.snapshots() call will silently receive nothing (and never receive updates, as if there was just no data to be found) if permission is denied (due to access rules on the DB) . So if you can see in the Firebase Console that data is there but your code is receiving no data — this may be the cause. In that case your app will likely be stuck at “Please wait…”. Using DocumentReference.get() would throw an Exception (e.g. as a once-off initial load action) that can be communicated to the user. Review the DB access rules in this case. This subtle issue is being tracked on GitHub <a href="https://github.com/FirebaseExtended/flutterfire/issues/1465">here</a> and <a href="https://github.com/FirebaseExtended/flutterfire/issues/185">here</a>.</li></ul><p>Finally, we need to update the CounterState constructor. Previously we had a lone call to _load(). Instead, we now need to initialise _myDevice and then begin listening for data from the DB. Recall that the constructor for the MyDevice class itself contains an async private method _setup() which calls notifyListeners() when the required values are accessible. So, in our CounterState constructor we must add listeners to _myDevice so that we can notify the UI that the data is ready to display. Here’s how we do that:</p><pre>CounterState() {<br>  _myDevice = MyDevice()<br>    ..addListener(() {<br>      notifyListeners();<br>    });<br>  // start listening for DB data<br>  _listenForUpdates();<br>}</pre><p>The ..addListener(…, in this case, is a short-hand for _myDevice.addListener(… (and the previous line would have to be terminated with a semi-colon). Writing it as above highlights that the listener needs to be added immediately so as to not miss any notifications that _myDevice may emit.</p><p>We’ll make some updates to lib/main.dart to better reflect the new shared setting that our app is in. Update the MyApp title line:</p><pre>title: &#39;Local Storage Demo&#39;,</pre><p>to instead be:</p><pre>title: &#39;Cloud Storage Demo&#39;,</pre><p>Similarly update the MyHomePage instantiation line:</p><pre>child: MyHomePage(title: &#39;Local Storage Demo&#39;),</pre><p>to instead be:</p><pre>child: MyHomePage(title: &#39;Cloud Storage Demo&#39;),</pre><p>Alter the text indicating the meaning of the counter:</p><pre>: counterState.isWaiting ? &#39;Please wait...&#39; : &#39;You have pushed the button this many times:&#39;,</pre><p>to be like so:</p><pre>: counterState.isWaiting ? &#39;Please wait...&#39; : &#39;The counter value is:&#39;,</pre><p>Finally, we’ll add two new lines of text indicating:</p><ul><li>which device last update the counter, and</li><li>the name of the device we’re running on right now</li></ul><p>Find these lines in the children of the main Column:</p><pre>counterState.hasError<br>  ? Text(&quot;Oops, something&#39;s wrong!&quot;)<br>  : counterState.isWaiting<br>    ? CircularProgressIndicator()<br>    : Text(<br>      &#39;${counterState.value}&#39;,<br>      style: Theme.of(context).textTheme.display1,<br>    ),</pre><p>and add these lines directly below. Note that we’re adding a Column inside the already existing Column. This is an example of the unlimited ability to compose widgets from other widgets:</p><pre>(counterState.hasError || counterState.isWaiting)<br>  ? Text(&#39;&#39;)<br>  : Column(<br>    children: [<br>      Text(&#39;last changed by: ${counterState.lastUpdatedByDevice}&#39;),<br>      SizedBox(height: 16.0),<br>      Text(&#39;(This device: ${counterState.myDevice})&#39;),<br>    ],<br>  ),</pre><p>So we are ready to run the code. Go ahead and start an Android Emulator or iOS Simulator, and do our first run:</p><pre>flutter run</pre><p>That first run may take a few minutes to complete the build, and bring up the app on the sim screen, as there is a lot of first-time compilation of the Firestore package. All going well you can now click the “+” button and see our counter increment. (<em>If you’re trying to build on iOS and hitting an error related to deprecated </em><em>timestampsInSnapshotsEnabled, then check the solution </em><a href="https://stackoverflow.com/questions/59188631/could-not-build-the-application-for-the-simulator-after-adding-cloud-firestore-t"><em>here</em></a><em> relating to </em><em>pod update ….</em>)</p><p>Time to share that data! Quit the flutter run and start up a second simulator/emulator concurrently — either of the same platform or one of each. Depending on your desktop/laptop memory and horsepower, you may even start three simulators. Ensure that flutter can see all of them in the output of:</p><pre>flutter devices</pre><p>Then run on all of them:</p><pre>flutter run -d all</pre><p>Then from any one of them click the increment button and notice how all devices update with the shared-counter value, within a moment. They also all indicate which device made the most recent update. Additionally, if you have your Firestore Database “Data” tab open in the browser, with the “shared” document selected you will see the data being updated when any device makes an update.</p><p>Note that, from the Firestore console in the browser, we can delete the individual database document fields, or even the entire document, the app will be notified immediately and react gracefully. Subsequently recreating the document will also cause the running app to react and become functional again.</p><p>The finished source code is available in my <a href="https://github.com/eggzotic/flutter_persistent_cloud">GitHub repo</a>. Remember that really only the source code (lib/ folder) and pubspec.yaml are of any use as you need to create your own Firestore project, database and access-rules as we walked thru above.</p><h3>Fun Firestore Facts</h3><p>So we have stepped up the persistent state storage — moving the authoritative source of our data into the Cloud. But…you may notice that since we removed the artificial-delay code, that you barely see the CircularProgressIndicator in the UI any more (i.e. we don’t seem to be waiting, as one might expect for such long-distance communications). There are a few reasons for this:</p><ul><li>The data-payload for this app (i.e. a number and a device-name-string) is really very small — nowhere near the 1 MB limit per document — so we’re not taxing the network in that sense.</li><li>Our code has separated the operations of storing a new value (via _save()) and receiving updates (via _listenForUpdates()).</li><li>Since processing updates is synchronous from the moment they arrive, only _save() actually involves any waiting-for-completion, and so it is the only one that may trigger the waiting-indicator.</li><li>Firestore by default, and completely transparently to our code, caches data locally on the device, meaning that “writes” (i.e. calls to setData()) complete very quickly without waiting for the data to traverse the network to the Firestore servers, or the corresponding acknowledgement. So it will be taking little more time/effort (for the local-write) than it did when we used SharedPreferences (and in that case we also saw no effective waiting time without including the artificial delay). The code considers the write complete once it is committed to local cache — hence the quick save.</li><li>Despite the local-cache providing the illusion that the data update is very fast, the reality for other devices is that they’ll not see the new data before the remote-write to the Firestore servers has completed. Hence, as you can see in the demo GIF above, one device can update the number multiple times before another device may see those updates.</li></ul><p>Our code is not transactionally safe. Firestore does support transactions that ensure only a single device is updating a database document at any point in time — forcing others to wait while the transaction completes. However for simplicity we have not covered that here and so we’re operating on a “last in wins” basis — the most recent update will be the one propagated. This may not be what you want in some cases! Be aware and use transactions if you need them.</p><p>Another Firestore feature we’ve not touched on in this article is offline-support. Again, by default and completely transparently, when your device cannot reach the Firestore servers, it will use (for both read and write) data from the local-cache, and automatically flush the writes to Cloud Firestore when the network connection is available again (unless it has never cached this data before (for reads), in which case you may receive errors). This may also cause some writes to arrive at the Firestore servers very late and overwrite an earlier (higher!) value. Note that transactions do not function when offline and will always cause your code to throw an error — so be ready to catch.</p><p>If you intend to store your new project in a GitHub repo then it’s best to exclude the Firestore files. They do not contain super-sensitive data but will trigger warnings from some of the security features of GitHub that scan for API keys in public repos. To do that, assuming you have already run git init, then add these lines to .gitignore:</p><pre># Google Firebase / Firestore related<br>**/ios/Runner/GoogleService-Info.plist<br>**/android/app/google-services.json</pre><p>If you had already added those files (e.g. if you had run git add --all), then you can remove them from the repo while leaving them on-disk:</p><pre>git rm --cached ios/Runner/GoogleService-Info.plist<br>git rm --cached android/app/google-services.json</pre><p>Subsequent git commit and git push commands will ensure that those files are not present on your public GitHub repo.</p><p>As mentioned earlier, for a scalable app with even modest data capacity and complexity requirements, database-access will most likely require the use of user-authentication, which can then be referenced in your Database “Rules”. Creating and managing users and passwords, and authentication methods with Firestore is available through the Firebase Console web portal. However the code to manage authenticating the user in the app is more complex and worth a separate article….now there’s an idea for a future article — stay tuned!</p><p>Previous episodes: <a href="https://medium.com/@eggzotic/local-data-persistence-in-flutter-7f82c54efe5">Local Data Persistence in Flutter</a>, <a href="https://medium.com/@eggzotic/stateless-flutter-2e14b6ae30b5">Stateless Flutter</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5fd7f1440f25" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/cloud-based-data-persistence-in-flutter-5fd7f1440f25">Cloud-based Data Persistence in Flutter</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Local Data Persistence in Flutter]]></title>
            <link>https://medium.com/swlh/local-data-persistence-in-flutter-7f82c54efe5?source=rss-63d3daebb8fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f82c54efe5</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[persistent-state]]></category>
            <category><![CDATA[sharedpreferences]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Richard Shepherd]]></dc:creator>
            <pubDate>Wed, 11 Dec 2019 02:45:03 GMT</pubDate>
            <atom:updated>2019-12-23T11:17:42.621Z</atom:updated>
            <content:encoded><![CDATA[<h4>Save my State</h4><h3>What?</h3><p>In my previous article <a href="https://medium.com/@eggzotic/stateless-flutter-2e14b6ae30b5">Stateless Flutter</a> we looked at the classic Flutter starter app, but refactored it to Stateless Widgets only, and introduced the Provider package for state-management. In this article we will go a step further by adding persistent-storage to our app state data.</p><p>Recall that the Flutter starter app has a single screen with a zero-initialised counter in the center of the screen, and a “+” button in the lower-right that increments that counter, by one, in response to each tap. However every time we re-start the app, the counter begins at zero again. There is no persistence of our state data.</p><p>From a user-experience perspective, the sole change to the App should be that each time the App is started afresh, the counter value carries on where it left off from the previous run. The change to the code, however, will be more significant — which sets us up well for future improvements (to come in a later article in this series). Additionally — we will enhance the App to include a reset-to-zero button — just to make it ever-so-slightly more interesting.</p><p>Here’s a look at the finished product on an iOS simulator, including showing that we close and kill the running App, followed by opening it afresh with the previous value (3) freshly loaded from SharedPreferences:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*9-OWUAaalZ0mGIhST5zrvA.gif" /></figure><p>The repo for the finished product above is at <a href="https://github.com/eggzotic/flutter_persistent_local">https://github.com/eggzotic/flutter_persistent_local</a>. But don’t go there yet! The learning is in the journey we follow below, especially in the “But really, how?” section. If, at the end of that, your app is not quite working — then refer to the link above to “close the gap” so you to can see the above on your desktop.</p><h3>Why?</h3><p>Most real-world apps will need to save some data that is referenced again and again — every time the app is used. Mobile OS, such as iOS and Android, manage the lifecycle of each running App — when an App goes into the background it may be forced to quit any time before the user next opens it. Regardless of whether the App was quit in between times, the next time the user opens the app it should behave and function the same (apart from some session-based apps, e.g. mobile-banking) as where they left off. An app may still be running from the last time it was opened, or it may need to open-from-scratch and any “state” may have to be reloaded. The App-code (yes, the code that we as developers write) needs to take care of this without the users having to concern themselves with whether that data has been appropriately stored for later access.</p><h3>How?</h3><p>Flutter offers us several ways we can achieve persistent data storage for our mobile Apps, including:</p><p>Local, on-device storage, e.g.:</p><ul><li>in a file</li><li>via key-value storage such as SharedPreferences</li></ul><p>Off-device storage such as:</p><ul><li>in remote object storage e.g. S3</li><li>in a relational-database (e.g. MySQL, PostgreSQL, …)</li><li>in a NoSQL database (e.g. MongoDB, Google Cloud Firestore)</li></ul><p>In this article we will augment our Stateless Starter App by adding persistent local (on-device) data storage using the <a href="https://pub.dev/packages/shared_preferences">SharedPreferences package</a>. This package provides a common method of storing key-value data locally for both iOS and Android. It avoids the overhead of file-handling (e.g. paths, open, close, check for existence, read, write, seek, permission-to-read/write?), allowing us to treat the store more like a map (aka associative array, hash-map, or dictionary, depending on your programming language roots).</p><h3>But really, how?</h3><p>Bring on the coding! To begin with either:</p><ul><li>Use (or clone) your finished project from the <a href="https://medium.com/@eggzotic/stateless-flutter-2e14b6ae30b5">previous article</a> as the starting point today, or…</li><li>…clone the repo from <a href="https://github.com/eggzotic/flutter_create_stateless">https://github.com/eggzotic/flutter_create_stateless</a> to your development environment — call this new repo “flutter_persistent_local”. This is the repo of the finished-app from my previous article <a href="https://medium.com/@eggzotic/stateless-flutter-2e14b6ae30b5">Stateless Flutter</a>, and it serves as our starting point for this new version. After pulling that down, you may need to run this at the terminal, from the top-level folder of the project, to resolve the initial errors in your IDE:</li></ul><pre>flutter packages get</pre><p>Open the pubspec.yaml file and add below the “provider: …” line:</p><pre>shared_preferences: ^0.5.4+8</pre><p>Also, update the name and description lines at the top of the file. Once you have updated the name (e.g. to flutter_persistent_local), you may also need to update the test/widget_test.dart file where an import line will be broken due to the package name change. Then run:</p><pre>flutter packages get</pre><p>Next, move the CounterState class out into its own file: Create the file lib/counter_state.dart and cut-n-paste the CounterState class definition out of main.dart into this new file. Add these imports to the top of the new file:</p><pre>import &#39;package:flutter/foundation.dart&#39;;<br>import &#39;package:shared_preferences/shared_preferences.dart&#39;;</pre><p>The first line will resolve the errors in CounterState class, while the second line we will use soon. Back in the main.dart file, add this import just below the existing ones at the top of the file:</p><pre>import &#39;counter_state.dart&#39;;</pre><p>At this point the app should compile and run as before. Go ahead and test it with a simulator/emulator:</p><pre>flutter run</pre><p>Time now to modify our CounterState class to include persistent storage of our state data. This is by far the most involved part of this article, but well worth the journey.</p><p>Previously we initialised the _value property to 0 every time we created an instance of CounterState. We will no longer do that, as instead we’ll be loading its value from SharedPreferences. So, modify the combined declaration/initialisation of _value to be a simple declaration only, i.e.:</p><pre>int _value;</pre><p>Also, near the top of the class definition, add the line below. We will use this constant as the key when loading/storing our state data (_value) from/to the key-value store of SharedPreferences. The string literal &#39;counterState&#39; can be any non-empty string, but should be meaningful, and after the code is run once (i.e. a value is stored with that key), it should not be changed again:</p><pre>static const _sharedPrefsKey = &#39;counterState&#39;;</pre><p>Loading/storing values from/to SharedPreferences is asynchronous. Even though it does not involve any network activity, the app is still interacting with the underlying OS (iOS or Android) and filesystem. Much of the complexity of that interaction is taken away from us — but not the fact that we have to <em>wait</em> on most of the calls. Most of the time it is very fast. However we must treat it much the same as in any other async situation.</p><p>This means that our code has to:</p><ul><li>wait for some functions to return values (using await)</li><li>indicate to the UI when waiting is required (e.g. introduce some transient state property)</li><li>be aware that errors can occur, beyond its control, that the user needs to know about, and the UI needs to handle gracefully (e.g. again, introduce some transient state property)</li></ul><p>So, we will add some transient state properties for this. Just below the declaration of _value and the getter value, add these lines:</p><pre>// transient state - i.e. will not be stored when the app is not running<br>//  internal-only readiness- &amp; error-status<br>bool _isWaiting = true;<br>bool _hasError = false;<br>//<br>// read-only status indicators<br>bool get isWaiting =&gt; _isWaiting;<br>bool get hasError =&gt; _hasError;</pre><p>The values of _isWaiting and _hasError will be set accordingly while waiting for data to be loaded/saved, when data is loaded, when saves are complete, when errors occur, and when operations complete successfully. Any time that any of our state properties change (i.e. _value, _isWaiting, _hasError), we need to call notifyListeners() so the the UI knows to update accordingly. We will see this below.</p><p>The most substantial new method to add will take care of loading and saving _value. Let’s start by adding this:</p><pre>// helper to do the actual storage-related tasks<br>//  handles both initial-load &amp; save since they only differ by essentially 1 line<br>//  - getInt vs setInt<br>void _store({bool load = false}) async {<br>  _hasError = false;<br>  _isWaiting = true;<br>  notifyListeners();<br>  // artificial delay so we can see the UI changes<br>  await Future.delayed(Duration(milliseconds: 500));<br>  //<br>  try {<br>    final prefs = await SharedPreferences.getInstance();<br>    if (load) {<br>      _value = prefs.getInt(_sharedPrefsKey) ?? 0;<br>    } else {<br>      // save<br>      // uncomment this to simulate an error-during-save<br>      // if (_value &gt; 3) throw Exception(&quot;Artificial Error&quot;);<br>      await prefs.setInt(_sharedPrefsKey, _value);<br>    }<br>    _hasError = false;<br>  } catch (error) {<br>    _hasError = true;<br>  }<br>  _isWaiting = false;<br>  notifyListeners();<br>}</pre><p>Some explanation of the above:</p><ul><li>we start by setting _isWaiting to true (essentially saying we’re busy until this method completes), and _hasError to false (nothing has gone wrong, yet) and notifying listeners (which happens to be the UI).</li><li><em>later, we will see how we use these to update the UI to indicate we’re waiting for something to complete</em></li><li><em>this situation applies to both load and save — both involve async operations</em></li><li>a half-second artificial delay is added here — enough time so that we can clearly see the UI update to reflect this “we’re waiting” state. You would not do this in a real app(!)</li><li>then we wait for a handle to the SharedPreferences shared instance. Even though this typically is very quick, it is not a synchronous operation and so we need to use await to ensure the code does not continue before we have that handle</li><li>next, we either load (getInt) or save (setInt) _value.</li><li><em>We’re using a single method to cover both load and save since the code required for these operations differ only in those 2 lines</em></li><li>We use the try { …} catch() { …} blocks to allow for possible errors that may occur while interacting with SharedPreferences.</li><li><em>If errors do occur, we set </em><em>_hasError to </em><em>true</em></li><li><em>If no errors occurred, we likewise set </em><em>_hasError to </em><em>false</em></li><li>Regardless, we finally set _isWaiting to false and notify the listeners.</li><li>in case you want to see what happens when an error occurs, one way this can be done is to uncomment the line in the code above where it throws an artificial exception. The value “3” can be set to anything — just click the increment button until that value is exceeded and you will get an error.</li></ul><p>With that method in place, we now define these convenience methods that leverage it for their respective operations:</p><pre>void _load() =&gt; _store(load: true);<br>void _save() =&gt; _store();</pre><p>The _load() will be used just once, when we create a new instance of CounterState. For that to happen, we need an explicit constructor for the class. Add it here:</p><pre>// default Constructor - loads the latest saved-value from disk<br>CounterState() {<br>  _load();<br>}</pre><p>The _save() will be used every time we update _value, to ensure our runtime state and persistent state are in sync. So we’ll define a new helper method _setValue, like so:</p><pre>void _setValue(int newValue) {<br>  _value = newValue;<br>  _save();<br>}</pre><p>We will change the definition of increment() and add a new method, reset(), that will set _value back to 0 — with a new control added to the UI to access this later (and as already shown in the GIF above). Delete the previous definition of increment and add these lines:</p><pre>void increment() =&gt; _setValue(_value + 1);<br>void reset() =&gt; _setValue(0);</pre><p>So that completes the transformation of our data-model class CounterState to include persistent storage.</p><p>Time to update the UI. Open main.dart. There are no changes to the MyApp widget. The MyHomePage widget will undergo some change though. Delete the convenience definitions of _counter and _incrementCounter() inside build.</p><p>Then locate the Column children lines:</p><pre>children: &lt;Widget&gt;[<br>  Text(<br>    &#39;You have pushed the button this many times:&#39;,<br>  ),<br>  Text(<br>    &#39;$_counter&#39;,<br>    style: Theme.of(context).textTheme.display1,<br>  ),<br>],</pre><p>and replace with these lines:</p><pre>children: &lt;Widget&gt;[<br>  Text(<br>    counterState.hasError<br>    ? &#39;&#39;<br>    : counterState.isWaiting<br>      ? &#39;Please wait...&#39;<br>      : &#39;You have pushed the button this many times:&#39;,<br>  ),<br>  counterState.hasError<br>  ? Text(&quot;Oops, something&#39;s wrong!&quot;)<br>  : counterState.isWaiting<br>    ? CircularProgressIndicator()<br>    : Text(<br>      &#39;${counterState.value}&#39;,<br>      style: Theme.of(context).textTheme.display1,<br>    ),<br>],</pre><p>In the above we’re using the values (true/false) of counterState.hasError and counterState.isWaiting to dictate the information displayed on the screen. We always follow this order: check for error, then check whether we’re still waiting, and if those are all false we finally we go ahead with the main information display. Every time notifyListeners() is called from methods of counterState, the screen will update accordingly. That half-second delay we added in CounterState._store ensures that we have some time to see the CircularProgressIndicator spinning on the screen (i.e. it ensures that counterState.isWaiting == true for long enough for us to see it). If CounterState.hasError is true, then we’ll get the “Oops, something’s wrong!” message, etc.</p><p>Finally, as a small enhancement to the UI, replace the lone “increment” floating-action-button:</p><pre>floatingActionButton: FloatingActionButton(<br>  onPressed: _incrementCounter,<br>  tooltip: &#39;Increment&#39;,<br>  child: Icon(Icons.add),<br>),</pre><p>with these lines, to get a “reset-to-zero” button to accompany it:</p><pre>floatingActionButton: Row(<br>  mainAxisAlignment: MainAxisAlignment.spaceAround,<br>  children: &lt;Widget&gt;[<br>    FloatingActionButton(<br>      child: Icon(Icons.undo),<br>      // colours indicate when the button is inactive (i.e when counterState is waiting)<br>      backgroundColor: counterState.isWaiting<br>        ? Theme.of(context).buttonColor<br>        : Theme.of(context).floatingActionButtonTheme.backgroundColor,<br>      // the button action is disabled when counterState is waiting<br>      onPressed: counterState.isWaiting ? null : counterState.reset,<br>    ),<br>    FloatingActionButton(<br>      child: Icon(Icons.add),<br>      // colours indicate when the button is inactive (i.e when counterState is waiting)<br>      backgroundColor: (counterState.isWaiting || counterState.hasError)<br>        ? Theme.of(context).buttonColor<br>        : Theme.of(context).floatingActionButtonTheme.backgroundColor,<br>      // the button action is disabled when counterState is waiting<br>      onPressed: (counterState.isWaiting || counterState.hasError)<br>        ? null : counterState.increment,<br>    ),<br>  ],<br>),<br>floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,</pre><p>Again, we use counterState.hasError and counterState.isWaiting to determine whether the buttons are enabled (onPressed is non-null) and colour them appropriately.</p><p>So we’re done with the code, go ahead and run the app:</p><pre>flutter run</pre><p>Even more importantly, after a few clicks, quit the app (while the counter is not zero(!)) and then run it again (on the same simulator, emulator or device!):</p><pre>flutter run</pre><p>This time the app will start with the counter showing the same value as when you previously quit it. Note that the value only persists when started/re-started on the same simulator, emulator or device. Our state is persistent, but still private to the specific device that created it.</p><p>For your reference, the repo for the final product is at <a href="https://github.com/eggzotic/flutter_persistent_local">https://github.com/eggzotic/flutter_persistent_local</a>.</p><h3>Prefer SharedPreferences?</h3><p>SharedPreferences provides simple and convenient local on-device storage for Flutter Apps. It’s also fast. And it’s free, on your own device.</p><p>But…beware these limitations and caveats:</p><ul><li>SharedPreferences does not provide a means to sync writes to disk. The underlying OS (iOS or Android) remains in control of this.</li><li>Due to the underlying platform-specific mechanisms (iOS — NSUserDefaults, Android — SharedPreferences) there will be various limitations:</li><li><em>simple builtin types only — e.g. numbers, strings, bool, binary-data</em></li><li><em>size-limits, entry-count-limits</em></li><li><em>storing other data-types typically requires encoding/decoding for every load and save operation — which means more effort in your coding to perform these operations, and may take more CPU resource and time to complete, which may impact the user-experience (and the device battery consumption)</em></li><li>When an App is deleted from the simulator/emulator/device then the data in SharedPreferences is also gone. Permanently.</li><li>There is no easy way to backup/protect the data stored in SharedPreferences, apart from device-level mechanisms (e.g. iCloud for iOS).</li><li>There is no easy way to inspect/debug the data stored in SharedPreferences, outside of the App that created the data.</li><li><em>during development you may add code/screens to read and display the data on your own devices and sims — this represents effort you may have to redo for every app</em></li><li><em>but once your App is “in the wild”, on other people’s devices — debugging issues related to their data-content is difficult, if not impossible</em></li><li>Related to the above point, if you add properties to your data-structures (e.g. in a later version of the App), when your code runs it needs to account for the data in SharedPreferences not having all these new properties. This can be harder to work with when you do not have another tool to inspect the current data.</li><li>any type of local-storage does not provide for data-sharing between devices and users</li></ul><p>So, stay tuned for the next edition where we will look at alternative persistent storage methods that overcome some of the above short-comings.</p><p>Next episode: <a href="https://medium.com/@eggzotic/cloud-based-data-persistence-in-flutter-5fd7f1440f25">Cloud-based Data Persistence in Flutter</a></p><p>Previous episode: <a href="https://medium.com/@eggzotic/stateless-flutter-2e14b6ae30b5">Stateless Flutter</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f82c54efe5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/local-data-persistence-in-flutter-7f82c54efe5">Local Data Persistence in Flutter</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stateless Flutter]]></title>
            <link>https://medium.com/@eggzotic/stateless-flutter-2e14b6ae30b5?source=rss-63d3daebb8fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e14b6ae30b5</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[google-flutter]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[dart]]></category>
            <dc:creator><![CDATA[Richard Shepherd]]></dc:creator>
            <pubDate>Tue, 03 Dec 2019 02:16:03 GMT</pubDate>
            <atom:updated>2019-12-16T08:14:18.506Z</atom:updated>
            <content:encoded><![CDATA[<h4>Providing for Purists</h4><h3>What?</h3><p>What are we here for?</p><p>In this article we’ll look at the classic Flutter starter project — but with Stateless Widgets only. The purpose is to demonstrate how to create an entire app without writing Stateful Widgets. In case anyone needs reminding, here’s a peek at the final state(!) of the app — oh so familiar, right?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*H6DbtDxyl9po0cPFmq9qRg.gif" /></figure><p>If you’ve not yet tried out Flutter, head on over to the home page at <a href="https://flutter.dev/">https://flutter.dev/</a>. If you’re familiar with Flutter already, but are asking questions like:</p><ul><li>how to manage real app-wide state?</li><li>how to more cleanly separate state-code from UI-code (than is possible using the builtin Stateful Widget)?</li><li>how to avoid explicitly passing state from widget-to-wrapped-widget … as we populate our UI and the widget-tree is getting deeper? Even across multiple screens (routes)</li><li>how to avoid using a big old Singleton for data state management!</li><li>I like the &lt;XXX&gt; state management approach, but the boiler-plate code requirements can be a hassle, is there something simpler?</li></ul><p>then these questions are addressed, to some extent, in this article.</p><p>The code for this alternate-starter-app is located at <a href="https://github.com/eggzotic/flutter_create_stateless">https://github.com/eggzotic/flutter_create_stateless</a>. The App looks and behaves (to the end-user) just like the default project that initially results from running flutter create …. Anyone who has installed flutter, and followed a beginner tutorial, has seen and used this starter-app. That familiarity is intentionally exploited here to show how to:</p><ul><li>achieve the same result while writing Stateless Widgets only</li><li>begin using the Provider package for app-state management</li></ul><p>Note that Provider is not the only choice available to separate, manage and facilitate access to the app state. Other options exist and it’s a matter of personal taste and preference as to which to use. When I happened upon Provider, I found it to be preferable to my previous approaches and have used it ever since — and have not yet had reason to move on. Note also that this is a separate issue from data-persistence. I will cover that in another article.</p><h3>Why?</h3><p>Why would we care about writing Stateless Widgets only?</p><p>For me, Stateless Widgets appeal due to their simplicity and clarity. A Stateless Widget contains final instance properties only, optional helper-methods, and a mandatorybuild method that describes the UI appearance for any given app-state. It does not defer its buildmethod to another State object (as in the case of Stateful Widgets) and has a simple lifecycle (again, compared to the more complex Stateful Widget + State object). The Flutter engine is optimised to ensure that visual updates to your app are limited to real-change, regardless of how much activity (i.e. re-builds) may be going on due to data-change.</p><h3>How?</h3><p>But my UI is not a static screen?</p><p>Does “writing Stateless Widgets only” imply the appearance can never change? Not at all. Stateless Widgets can access (&amp; modify) data passed in from outside, e.g. through dependency injection. When a Stateless Widget is instantiated, the build method is run to determine its initial appearance. And that build method can be re-run to reflect the updated state of our App.</p><p>But, there is no setState() to be used with Stateless Widgets, so how can we trigger a re-build when app-state has changed?</p><p>Well, there is the option of using StreamBuilder — but that may require us to jump through some hoops for our data-model to also produce Stream(s) to be consumed by the StreamBuilder. For data naturally suited to Streams (or already being produced as a Stream — e.g. using FlutterFire with Google Cloud FireStore’s snapshot().listen()), then by all means use StreamBuilder to manage the display as the Stream produces data-updates. But in other cases that may seem unnatural, and require more code.</p><p>Enter … the Provider package (<a href="https://pub.dev/packages/provider">https://pub.dev/packages/provider</a>). Among others, Provider includes a variant ChangeNotifierProvider which can both contain our app state and trigger updates (i.e. trigger build to re-run) of any consumer — such as a Stateless Widget, by notifying said consumer without the widget having to provide an explicit callback. Provider, in fact, offers several variants — e.g. using Stream, Future, … — but this article will be limited to demonstrating the ChangeNotifierProvider, which also happens to be the one I’ve used most often in Apps.</p><h3>But really, how?</h3><p>So, down to the business of how this alternate starter app is written. The app source code remains a single-file of dart code — main.dart, for convenience — but this is not best practise for a real project. Feel free to go one better and separate the dart state (CounterState, below) to a dedicated source file under the projectlib/ folder. The original main.dart that flutter create … generates (Stateful Widget and all) is present in the repo, renamed to main.dart.orig, for reference. For this article the intent is to add/remove minimal code to complete the transformation (from Stateful + State -to- Stateless + Provider) while keeping the code (and the running-app) as recognisable as possible.</p><p>The instructions below will take you from flutter create … to an end result as described &amp; discussed above. Although I personally use Visual Studio Code (VS Code) + iOS Simulator as my main IDE + testing platform — the below steps do most of the non-editing using the bash command-line from the terminal, which hopefully keeps it applicable to the broadest audience. It is assumed you have already installed Flutter, plus Xcode and/or Android Studio etc. on your development machine.</p><p>While you can just download the repo and fire it up (via flutter run) — please don’t! Instead, by following the conversion process below, we’ll get a better feel for the effort involved in using Stateless Widget + Provider and for what it replaces/provides-an-alternative-to. Learning to appreciate that is the most value here.</p><ol><li>run flutter create flutter_create_stateless to create a new vanilla Flutter starter project (or choose your own project name)</li><li>open the project folder in your preferred editor/IDE</li></ol><p>Now we’ll introduce the Provider package:</p><ol><li>Open the pubspec.yaml file and locate the dependencies: section</li><li>Add provider: ^3.2.0, indented appropriately to match the other items. Version 3.2.0 was current at the time of writing this article.</li><li>next, run flutter packages get, if your IDE does not do this automatically.</li><li>Now open main.dart</li><li>Add this import statement near the top, just below the existing one for material.dart: import ’package:provider/provider.dart’;</li></ol><p>Now we’re all set to use Provider.</p><p>Next we’ll create a new class for containing the app-state. The original app essentially has a single int as state — the number that increments as we tap the floating button at the bottom of the screen. Super-simple — even too simple for a real app — that’s why it’s a starter app(!). A new class to manage a single int? Overkill, maybe, but that’s what reference projects often do — it serves to keep the focus on the mechanism (Provider) and avoid getting distracted with genuine data-model complexity.</p><p>So, create the CounterState class. Add the definition to main.dart (or go a step further and create a new file, and add the import to main.dart for it):</p><pre>class CounterState with ChangeNotifier {<br>  // the actual state is private (hence the leading &quot;_&quot;)<br>  int _value = 0;</pre><pre>  // this allows us read-only access to the state, which<br>  //  ensures modification of state is via public methods<br>  //  we expose (in this case that means &quot;increment&quot; only)<br>  int get value =&gt; _value;</pre><pre>  // how we modify state and notify consumers (e.g. the App UI)<br>  void increment() {<br>    _value += 1;<br>    // notify the consumer of this data that something has been<br>    //  updated - thus avoiding any need for setState()<br>    notifyListeners();<br>  }<br>}</pre><p>Key points to note about this class:</p><ol><li>with ChangeNotifier is in the class declaration. This <strong>enables</strong> instances of CounterState to notify any object that has registered a listener, on this instance, that a change may have occurred. ChangeNotifier is a builtin Flutter class described at <a href="https://api.flutter.dev/flutter/foundation/ChangeNotifier-class.html">https://api.flutter.dev/flutter/foundation/ChangeNotifier-class.html</a>.</li><li>notifyListeners() called immediately after modifying the state. This is <strong>how we notify</strong> listeners that a change really has occurred. When that listener is a Stateless Widget, this amounts to a re-build.</li><li>CounterState is not a plain-dart (i.e. flutter-less) class. ChangeNotifier is a Flutter class. But apart from the class declaration, and judicious use of notifyListeners(), our class code is near enough to pure dart. Another option, for a bit more separation of concerns, is to wrap a plain-dart class in a with ChangeNotifier intermediary class which in turn handles the public API for the pure-class so that notifyListeners() can be called when necessary. This approach might be useful when that inner plain-dart class is written by a 3rd-party!</li></ol><p>Beyond such a trivial piece of state to manage: In this class we call notifyListeners() just once — in the method where state is modified. For a real app, the state will be more complex — there may be multiple methods that will modify state. Include a call to notifyListeners() after updates to state are completed. If you have chained calls, you might include notifyListeners() in the lowest-level method only — where they all meet. E.g. if there are 3 public methods that all modify the same piece of state — but all call a common private helper-method that does the actual modification(s), then it may be best to have that private method be the only one that actually calls notifyListeners(). Try to avoid having a single state-modification that calls notifyListeners() more than once in the same update. But I digress.</p><p>That’s it — our state is ready to be used, aka “consumed”.</p><p>Back to main.dart (in case you created the above CounterState in a separate file).</p><p>The top-level Widget in our App is MyApp — a Stateless Widget, whose build method returns a MaterialApp — no change (yet).</p><p>The MyHomePage Widget — we will convert this to a Stateless Widget:</p><ol><li>Modify the declaration to class MyHomePage extends StatelessWidget</li><li>delete from @override _MyHomePageState … to the end of the void _incrementCounter() method definition.</li><li>Also, update the line title: Text(widget.title), to be slightly simpler as: title: Text(title), since we no longer have the 2-piece widget — we can access the title string directly.</li></ol><p>This has deleted the closing of the MyHomePage class and the opening of the class _MyHomePageState. The build method that previously belonged to the State object is now the build for our Stateless Widget. So, right now, our MyHomePage class has an instance property title and a build method … and some errors, due to _counter and _incrementCounter being now undefined.</p><p>How to introduce some state for our widgets to use?</p><p>Firstly we’ll go back to the MyApp widget and its build method. Locate the line home: MyHomePage(title: ‘Flutter Demo Home Page’),. We’ll change that line, to instantiate a CounterState object, wrapped in a Provider, like so:</p><pre>home: ChangeNotifierProvider(<br>  create: (context) =&gt; CounterState(),<br>  child: MyHomePage(title: &#39;Stateless Flutter Demo&#39;),<br>),</pre><p>Now the MyHomePage Widget has a CounterState instance attached just above its own context. But how to access &amp; modify that?</p><p>In the build method of MyHomePage, just below the method declaration, add these lines:</p><pre>final counterState = Provider.of&lt;CounterState&gt;(context);<br>final _counter = counterState.value;<br>void _incrementCounter() =&gt; counterState.increment();</pre><p>Having obtained a handle to our state (contained in counterState above), we can do anything with it… muahaha.</p><p>The magic to make our state object accessible from inside the widget is the Provider.of&lt;…&gt;(context) call. The type of object we’re looking for is included inside the angle-brackets &lt;…&gt;. Specifying the type is required so that the correct Provider object is found — there could be multiple, of different types, in a real world app. Notice that context is required as a starting point in the widget tree from which to search (upwards) for the app-state. Stateless Widgets only provide access to their build context within the build method. Since much of the logic determining the widgets appearance will likely be based on the values within the state, we essentially must bring all of that code into the build method. So, our Stateless Widget code will be largely concentrated in the build method — this might be something to consider if you’re averse to bloated build methods. De-bloating our build methods can still be achieved, after obtaining a handle to our state via Provider.of, by either having other methods defined in our Stateless Widget (to which we explicitly pass our state handle) which are then called from within build. Another way is breaking the content of those methods out into their own new custom Stateless Widgets (which can also access the Provider state data via Provider.of&lt;…&gt;(context)), since they will be even lower in the widget-tree.</p><p>Having now gained access to the data and methods of the CounterState object, we can read the value (_counter) and modify it (via _incrementCounter) exactly as was done before — hence we don’t need to modify any more code below this point. Continued use of private vars (i.e. those whose name begin with underscore) in build here is only to avoid altering more of the original code. No need to to this in your own projects written Stateless from the beginning.</p><p>Ensure you have a Simulator (iOS) or Emulator (Android) running or a physical device attached and go ahead with flutter run to see the app running. It should look and operate…exactly like the original start app. But you will have that warm, smug satisfaction that comes from being a purist and zealot of Stateless-ness!</p><h3>Down with the State(ful Widget)?</h3><p>So are Stateful Widgets dead? Can we banish them — to far off lands — to be used by those so wholly unsophisticated as to not appreciate a life of blissful Stateless-ness?</p><p>Well … no.</p><p>Stateful Widgets still have a place, even for us Stateless purists. The distinction between “App State” and pure “UI State” is one way to distinguish which way to go. For the former, we might prefer State management such as Provider (or BLoC, etc.). For the latter (pure UI state), Stateful Widgets may be more concise. Many of the Flutter builtins are in fact Stateful Widgets. One I use often is the ExpansionTile — this widget, when the user taps it, will toggle animating between an expanded form (show detail) and a more brief form (hide detail). Internally, ExpansionTile maintains a boolean state that determines whether that tile should be displayed as expanded or not, using setState() to update its appearance.</p><p>The beauty of Stateful Widgets is that we can <em>use</em> them without having to <em>write</em> them. They’re typically self-contained, often including animations and whatever other localised-state necessary for maintaining their UI appearance, that can then form the building blocks of our own Stateless Widget code. So if, like mine, your app UI is composed mostly of the built-in Flutter Widgets (and perhaps some excellent 3rd party ones), then we get the best of both worlds — we can <em>use</em> Stateful Widgets (without even knowing they are!) as components of the Stateless Widgets that we <em>write</em>.</p><p>Next episode: <a href="https://medium.com/@eggzotic/local-data-persistence-in-flutter-7f82c54efe5">Local Data Persistence in Flutter</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e14b6ae30b5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>