<?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 MELLATI Fatah on Medium]]></title>
        <description><![CDATA[Stories by MELLATI Fatah on Medium]]></description>
        <link>https://medium.com/@meltft?source=rss-818757b53c98------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*4siP-w8ZWzyq1nsLlQM0oA.png</url>
            <title>Stories by MELLATI Fatah on Medium</title>
            <link>https://medium.com/@meltft?source=rss-818757b53c98------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 01:03:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@meltft/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[Immutable State Management Rebuilder. How to refactor to immutability and vice versa.]]></title>
            <link>https://medium.com/flutter-community/immutable-state-management-rebuilder-how-to-refactor-to-immutability-and-vice-versa-b9576d6744f2?source=rss-818757b53c98------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9576d6744f2</guid>
            <category><![CDATA[immutable]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[MELLATI Fatah]]></dc:creator>
            <pubDate>Wed, 03 Jun 2020 10:01:01 GMT</pubDate>
            <atom:updated>2020-06-03T10:01:01.202Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/671/1*_kUoQKgydX8fFP-N6FqiYQ.png" /></figure><p>Do you agree with <em>Joshua Bloch</em> in <a href="http://www.amazon.com/exec/obidos/ASIN/0134685997/ref=nosim/javapractices-20"><em>Effective Java</em></a><em> when he stated that </em><strong>Classes should be immutable unless there’s a very good reason to make them mutable?</strong></p><p>Do you like functional programming where any mutation is considered as an unwanted side effect?</p><p>Do you believe that immutable objects :</p><ul><li>are simpler to construct, test, and use</li><li>enhance code predictability and give guarantee about their state to all object depending on it</li><li>are much easier to cache</li><li>And many more …</li></ul><p>Do you believe in all that but still feel lazy using immutability because of its state management difficulty?</p><p>In this article I will show you a straightforward and an easy to implement immutable state management solution using <strong><em>states_rebuilder </em></strong>package.</p><p><strong><em>states_rebuilder </em></strong>is a state management solution that differs from other good competitors by:</p><ul><li><strong>Business logic is 100% separated.</strong> Write your business logic with pure dart class without depending on any external library (<strong><em>Flutter </em></strong>and <strong><em>states_rebuilder </em></strong>included).</li><li><strong>Manage the immutable and immutable state.</strong> You are free to use immutable or mutable objects or to mix them. Even you can refactor to immutability (or mutability) without affecting the user interface.</li><li><strong>Very rich dependency injection system.</strong> Asynchronous dependency is injected with the same ease as synchronous dependency.</li><li><strong>Side effects without the <em>BuildContext</em>.</strong> Navigate, get the <strong><em>ScaffoldState</em></strong>, <strong><em>ThemeData</em></strong>, or <strong><em>MediaQuery </em></strong>without <strong><em>BuildContext</em></strong>.</li></ul><p>To focus only on the state management part, I choose to clone the provider_shopper from the <a href="https://github.com/flutter/samples/tree/master/provider_shopper">official Futter sample repo</a> with some added requirements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*1M3Iu9LIn4WJGEQ4.gif" /><figcaption><a href="https://github.com/flutter/samples/tree/master/provider_shopper">provider_shopper</a></figcaption></figure><p>The added requirements are:</p><ul><li>The list of products will be asynchronously loaded from a fake server. While loading the products a <strong><em>CircularProgressIndicator </em></strong>will be shown. If the server fails, a <strong><em>AlertDialog </em></strong>will be displayed with information about the error and a retry button to try another fetch.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*oNELn2wfIJaZG49qsRxHHA.gif" /></figure><ul><li>Products can be removed from the list by swiping them out of the list. The removal process is done optimistically. In other words, after removing a product, it is instantly removed from the list and an asynchronous call is sent in the background to the server to remove the product. If the server fails, the deleted product is returned to the list and a <strong><em>SnackBar </em></strong>is displayed to indicate to the user the nature of the error.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*k_a_iaAio0V_0OQ4QV44SQ.gif" /></figure><h3>The business logic part</h3><h4>catalog_state.dart</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bd508814e85093f6f4726a0eb8338bc8/href">https://medium.com/media/bd508814e85093f6f4726a0eb8338bc8/href</a></iframe><p>What’s the point here:</p><ul><li><strong>CatalogState </strong>is a pure vanilla dart class without extension or use of any external library. (no more worry about code sharing).</li><li>All methods return a new instance of <strong>CatalogState</strong>. Mutating an immutable object is creating a new object that reflects the mutation.</li><li>Methods are pure function.</li><li>If the result of an asynchronous method is unpredictable, we have to wait for it and meanwhile display a wait widget. In such a case, we use <strong>Future</strong>. Fetch a list of items is an example of an unpredictable asynchronous task (<strong>getItems</strong>)</li><li>If the result of an asynchronous method is predictable, it is wise to use the expected result and simply trust the backend service. If the backend service fails, we can return to the state just before calling the async method and display an error message. In such a case, we use <strong>Stream</strong>. Deleting an item is an example of a predictable asynchronous task (<strong>deleteItem</strong>).</li><li><strong>Optionally</strong>, we can define a class that extends <strong>CatalogState </strong>to specify the initial state.(<strong>CatalogInitialState</strong>).</li></ul><h4>catalog_state.dart</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7eea06a30d7dd1141ade06f63e985072/href">https://medium.com/media/7eea06a30d7dd1141ade06f63e985072/href</a></iframe><p>Methods can be static. In this case they accept the current state as parameter.</p><p>That’s all for the business logic part of the app.</p><h3>The UI part</h3><h4>main.dart</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e735e6719877fef30073c1db48364ae/href">https://medium.com/media/5e735e6719877fef30073c1db48364ae/href</a></iframe><p>We use the <strong>Injector </strong>widget to inject our dependencies.</p><p><strong>MyCatalog widget:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e53146ccbb159fd48436e7691f53cd1/href">https://medium.com/media/9e53146ccbb159fd48436e7691f53cd1/href</a></iframe><ul><li>Line 4–11: We used <strong><em>WhenRebuilder </em></strong>widget to subscribe to a new <strong><em>ReactiveModel </em></strong>widget created using the future method. The future method exposes the current state of its async state. From the exposed state we invoked <strong><em>getItems </em></strong>method.</li><li>Line 13–35: We used <strong><em>onSetState </em></strong>parameter to invoke side effects. Here we check for the error state and display an alert dialog. From the displayed alert dialog we used the exposed <strong><em>ReactiveModel </em></strong>to call the <strong><em>getItems </em></strong>again using the <strong>refresh()</strong> method.</li><li>Line 36–39 : We defined the corresponding widget for <strong><em>OnIdle</em></strong>, <strong><em>onWaiting</em></strong>, <strong><em>onError</em></strong>, and <strong><em>onData </em></strong>status.</li><li>Line 39–65: When the list of items is ready we display it. We wrapped the list of items inside a <strong><em>StateBuilder </em></strong>widget and subscribe it to the global <strong><em>ReactiveModel </em></strong>because we want to rebuild the list items after deleting an item.</li></ul><p><strong>MyListItem widget:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e88f361d34b1a33afc5f329ce1c5735/href">https://medium.com/media/7e88f361d34b1a33afc5f329ce1c5735/href</a></iframe><ul><li>Line 6–4: Get the T<strong><em>hemeData </em></strong>without the context. It is equivalent to final textTheme = Theme.of(context).textTheme.headline6 inside the build method.</li><li>Line 9–17: Get the ScaffoldState without the context and call <strong><em>showSnackBar </em></strong>method</li><li>Line 25–35: Get the global registered <strong><em>CatalogState ReacitveModel </em></strong>and call <strong><em>setState</em></strong>. <strong><em>setState </em></strong>exposed the current state. Using the current state we invoked the <strong><em>deleteItem </em></strong>method. The <strong><em>onError </em></strong>callback will be invoked if the <strong><em>deleteItem </em></strong>method throws.</li></ul><p><strong>AddButton widget:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/46bfa905a40c9a9d659f8c68079bbadd/href">https://medium.com/media/46bfa905a40c9a9d659f8c68079bbadd/href</a></iframe><ul><li>Line 8: Get the registered instance of <strong><em>CartState ReactiveModel </em></strong>and assign it to the <strong><em>cartRM </em></strong>final variable.</li><li>Line 14–22: Invoke <strong><em>setState </em></strong>to mutate the state. Using the exposed current state of the <strong><em>CartState </em></strong>we call the add static method.</li><li>Line 23: Get the registered instance of <strong><em>CatalogState ReactiveModel </em></strong>and call the notify method to notify its listeners.</li></ul><h3>Refactor to mutability and vice versa</h3><p>The interesting thing about <strong><em>States_rebuilder </em></strong>is that you can refactor to mutability or refactor to immutability without changing a single line of user interface code.</p><p>Here is the mutable version of <strong><em>CatalogState</em></strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c8ec4e629bfe755426250c850901ac0/href">https://medium.com/media/2c8ec4e629bfe755426250c850901ac0/href</a></iframe><p>With <strong>states_rebuilder</strong>, you can work with mutable objects (or immutable), and, in the future, if you want to move to immutable objects (or mutable), just make the required change to your business logic and that’s another level of separation of concerns.</p><p><a href="https://github.com/GIfatahTH/states_rebuilder_shopper">Here is the sample working code.</a></p><p>The immutable state can be managed with the Redux approach. The <strong><em>flutter_bloc </em></strong>library is the most popular package for managing the state immutably. <a href="https://github.com/GIfatahTH/states_rebuilder/tree/master/examples/009-todo_mvc_the_flutter_bloc_way">Here is the TodoMVC sample app rewritten following the flutter_bloc style but using states_rebuilder</a>.</p><p>For more information on the <strong>states_rebuilder </strong>library, see the official pub.dev page</p><p><a href="https://pub.dev/packages/states_rebuilder">states_rebuilder | Flutter Package</a></p><p>Feel free to try the <strong>states_rebuilder </strong>package and clap 👏 star 🌟 and the thumbs up 👍 it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9576d6744f2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/flutter-community/immutable-state-management-rebuilder-how-to-refactor-to-immutability-and-vice-versa-b9576d6744f2">Immutable State Management Rebuilder. How to refactor to immutability and vice versa.</a> was originally published in <a href="https://medium.com/flutter-community">Flutter Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Clean Architecture with states_rebuilder has Never Been Cleaner]]></title>
            <link>https://medium.com/flutter-community/clean-architecture-with-states-rebuilder-has-never-been-cleaner-6c9b91c3b9b6?source=rss-818757b53c98------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c9b91c3b9b6</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[dart]]></category>
            <dc:creator><![CDATA[MELLATI Fatah]]></dc:creator>
            <pubDate>Thu, 16 Jan 2020 00:09:15 GMT</pubDate>
            <atom:updated>2020-01-16T02:12:34.779Z</atom:updated>
            <content:encoded><![CDATA[<p>No matter how good your programming skills are and how many design patterns you master, for the enterprise-wide application, you have to architect your application in a way that makes it readable, maintainable, testable, and extensible. In this article, I will show you how to implement The Clean Architecture by taking advantage of the KISSness of <strong>states_rebuilder</strong>.</p><h3>What is an Architecture and why?</h3><p>َ An architecture is a way to factor your code into functional segments (inside folders and files) and keep clean boundaries between them so that it is easy to understand, easy to refer yourself inside and easy to modify as the project grows.</p><p><strong>First scenario: A real-life example of no architecture:<br></strong>Imagine that your home library has about ten books. No matter how you organize it, you can easily find the book you want the time you want.</p><p><strong>Second scenario: A real-life example of an architecture:<br></strong>Now, imagine you work in a university library with thousands of books. Then, you have to follow a convention of book arrangement. You may classify the books by subjects, language, author name or alphabetically. No matter your philosophy of the arrangement, you have to stick to one architecture so that when a student needs a particular book, you know exactly where to find it with your eyes closed.</p><p><strong>In the software development realm:</strong></p><p>You encounter the first scenario in tutorials and demo apps. The tutor aims to explain a particular aspect of the programming language. He can, without loss of clarity, put all the code inside one file. In demo apps, the app is in general small without any concern for future change. In these cases, wasting time following a particular architecture and organizing the code in folders and files will be overkilling for the tutor and confusion for the reader.</p><p>The second scenario is the situation of real-world enterprise apps. Real apps request for maintainability, extensibility, testability. To fulfill this request, the app code must be clean. The cornerstone of clean code is clean and effective architecture.</p><p>the benefit of a good architecture<br>1- <strong>Maintainability</strong>: no messed code, no cross-referencing between segments.<br>2- <strong>Scalability</strong>: You can add new functionality more easily<br>3- <strong>Testability</strong>: You can mock dependencies.</p><p>All the above three features are tightly related to change. No matter how well you design an application, over time an application must change. It must change to fix bugs (maintainability). It must change to grow (Scalability). But what about testability and how it is linked to change? Look at this sample of code:</p><pre>int counter=0;<br>void increment(){<br> counter++;<br>}</pre><p>It is easy to write a test to the<strong> increment()</strong> method to verify that the counter variable is incremented by one after executing the method. But what a big deal! Isn’t this ridiculous and a waste of time! No matter how complex the method is, one can verify that it works as expected by other means than unit testing. Why testing? the answer is the change. Let’s say that the requirements changed and you edited the <strong>increment()</strong> method to be :</p><pre>int counter=0;<br>void increment(){<br> incrementerService(counter);<br>}</pre><p>Now after this change, by running the test again you can track any unwanted behavior following the change (perhaps <strong><em>incrementerService(counter)</em></strong> return the wrong result). If you don’t have any test and the change causes bugs in your program, it will be difficult to track where did you get it wrong. Testing is an early detection utility of bugs after code refactoring.</p><p>Testing your code has another important benefit. If you follow good design patterns and clean architecture, you make your code testable, on the other flip side the easiness of writing tests witnesses the good quality of your code and in the same sense trouble writing tests is a good sign of the bad quality of your code. If you want to take your skills to the next level, shift the gears and consider Test Driven Development TDD. In TDD, you write the test before even writing a single line of code. It seems a little strange to test inexistent code and one can not resist coding first especially at the early stage of the app when you are not clear about what exactly you want. Just look at this approach the same way as setting your goals in project management before starting your project. If your vision is clear, your goals will be clear and the reverse is true.</p><p>In case of bug fixing or new feature adding, TDD is a must. Before fixing a bug try to write a test that reproduces the bug; if succeded you find yourself understanding the origin of the bug. And as has been said, understanding the problem is half of the solution. After fixing the bug, and by running all new and old tests you are one hundred percent sure that you fixed the problem without any unwanted side effect.</p><p>If you are adding a new requested feature, your intention is so clear that writing a test that expects the requested feature is very easy, and by looping between Red, Green, and refactor technique of TDD you can come out with the best solution. Again after changing the code run all the tests to check the validity fo your code.</p><p>Do not underestimate tests and be sure that the time you spend writing tests will save your life in the future.</p><h3>The clean layered architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/487/1*RLaOoscT3DErCg1uFfoHNQ.png" /></figure><p>The architecture consists of something like onion layers, the innermost layer is the <strong>domain layer</strong>, the middle layer is the<strong> service layer</strong> and the outer layer consists of three parts: the <strong>user interface</strong> UI, <strong>data_source </strong>and <strong>infrastructure</strong>. In coding, each of the parts of the architecture is represented using a folder. So the topmost folders are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/114/1*euimDqPws1aBRc0sHuNvSg.png" /></figure><p>Arrows in the picture above indicate code dependencies which can only point inwards. Nothing in an inner circle can know anything at all about something in an outer circle. In particular, the name of something declared in an outer circle must not be mentioned by the code in the inner circle.</p><p><strong>1- Domain (or Domain Model):</strong></p><p>It is the core of your app’s business logic, It contains all the logic pertaining to the business domain. By the way, if you want to switch gears again and take your programming skills to the next level, don’t waste more time and consider <strong>Domain-Driven Design (DDD)</strong>. In the context of DDD, experts in the problem domain work with the development team to get out with what is called the <strong>analysis model</strong>. The implementation of the analysis model is the <strong>domain model</strong> and this is what this folder should contain. If you are working on an app for yourself, you are the domain expert and the developer at the same time, so you have to think with your self to get out with mental models of the business using a common language that anyone of the same business can understand. This mental model free from any technical details is the <strong>analysis model</strong>. The domain model is the traduction of the analysis model in terms of code using the common language of the business (ubiquitous language).</p><p>The domain folder contains at least four subfolders.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/138/1*kS0m8Ix21m-S5y4atMfG_A.png" /></figure><p><strong>entities folder:</strong> Entities are mutable objects uniquely identified by their IDs. In most cases, entities are the in-memory representation of the data that was retrieved from the persistence store (data_source). An entity can have methods it must encapsulate all the domain logic it controls. Among the logic that should an entity have is the validation logic, which will be executed just before persisting the entity state to ensure that has the right state.</p><blockquote><strong>entities </strong>must be validated just before persistance</blockquote><p><strong>value objects folder:</strong> Value objects are immutable objects which have value equality and self-validation but no IDs. Value objects come to the rescue if you have many primitive fields in your entities. In this case, it may be possible to move some of them with the associated behavior and validation to a new value object classes. Validation is performed at the time of construction so that value objects are either instantiated in the right state or an error is thrown.</p><p>Value objects are such a good concept that you do keep refactoring your code to get more of them.</p><blockquote><strong>value objects </strong>must be validated the time of constraction</blockquote><p>NB: This is by no means a comprehensive tutorial on TDD or DDD. For more details on both concepts see the following reference:</p><p>1- Test-Driven development: <a href="http://agiledata.org/essays/tdd.html">link</a><br>2- Domain-Driven Design:<a href="https://martinfowler.com/bliki/BoundedContext.html"> link</a></p><p><strong>exception folder: </strong>This folder should contain all exception classes that entities and value objects are expected to throw.</p><p><strong>common folder:</strong> contains common helper utilities shared inside the domain (constants, enumerations, util classes …).</p><p>This is not an exhaustive list of folders, you can add any number of folders that will help you organize your domain logic.</p><p><strong>2- Service layer:</strong></p><p>The second layer is named <strong>service </strong>for it holds the <strong>application service </strong>layer. The <strong>application service</strong> layer is the client of the domain layer. It hides (or in technical terms “abstracts”) the details of the domain and exposes a programming interface (API) to represent the business use cases and behavior of the application. it is all about coordination and orchestration through delegation to domain and external services. The service layer must inversely depend on external services (Infrastructure and data_source) and this is done by defining a set of interfaces that should any external service implement. The set of interfaces defined is placed in the <strong><em>interfaces </em></strong>folder.</p><p>The service folder is made up of at least three subfolders.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/116/1*a1pgXXiPBNKbn8pHM7ZsPQ.png" /></figure><p><strong>interfaces folder: </strong>contains interfaces that should any external service implement.</p><p><strong>exception folder: </strong>This folder should contain all exception classes that the services classes and external service are expected to throw. External services in the infrastructure and data_source layer should not throw their own defined exceptions, but their errors should be caught and custom exceptions defined in this folder should be thrown instead.</p><p><strong>common folder:</strong> contains common helper utilities shared inside the service layer (constants, enumerations, util classes …).</p><p><strong>3- Infrastructure:</strong></p><p>Applications may rely on external resources, i.e; getting persistent data, fetching web, make a call or send a message or email, using 3rd-party libraries. In this case, the code using API of these third-party libraries is contained in the <strong>infrastructure </strong>folder (<strong>infrastructure layer</strong>). The service layer must communicate with the infrastructure layer through interfaces and infrastructure must implement interfaces defined in the service layer. This decoupling is mandatory to ensure our app does not depend on any 3rd-party library.</p><p>It is here the right place to put all the logic that deals with communication with platform-specific services such as sending emails, checking network connection, using GPS service, camera …</p><p><strong>4- data_source:</strong></p><p>Data_source is just a detail like the infrastructure, but it is such an important detail that gives it the merit of having its own folder. data_source is responsible for orchestrating the fetching and the persistence of data from one or more sources (API calls to a server, a local database, or both). It is here where the row data is converted to entities and value_object.</p><p><strong>5- UI folder:</strong></p><p>The UI is concerned only with the visual aspects of the application. In flutter, UI views have a top-level widget that contains other widgets, which contain other widgets and so on until you get to the leaf widget.</p><p>The UI folder contains at least four subfolders.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/113/1*HswurFWgs2D7MIqkUp75BA.png" /></figure><p><strong>pages folder: </strong>Since a UI is a collection of pages that the user can navigate between them, the first subfolder of the UI folder is the <strong><em>pages </em></strong>directory. Typically, you dedicate a folder for each page even if it has one file. The advantage of dedicating one folder for a page is to increase readability.</p><p><strong><em>widgets:</em></strong> It contains small reusable widgets that should be independent of the application. They can be used in other applications with a simple copy and paste and with little change if necessary. For example, this folder may contain your best-designed <strong><em>FAB</em></strong>, your super attractive <strong><em>CircularProgressBar</em></strong>, your awsome list tile … etc. By the time you constitute your custom widget library and you know where to find them if you need them in other apps.</p><p>Even if you are using widgets from external libraries, it is more convenient to adapt their interface and create your own and use yours throughout the user interface (this is a practical case of the adapter model). Your advantage is to dissociate your user interface from the concrete implementation of external libraries, and in the future, if you change your mind and decide to use another library, you will change one place: here inside the <strong><em>widgets </em></strong>folder.</p><p><strong>exception folder: </strong>Here you handle exceptions thrown from the domain and service layer.</p><p><strong>common folder: </strong>contains common helper utilities used in the UI layer (constant, enumeration, style, util classes …).</p><p>A big enterprise app may have many areas of interest. By area of interest, I mean an ensemble of related tasks and use cases that share the same knowledge to achieve common goals. In this case, each area of interest can have its own architecture as described above. In domain-driven design, these areas of interest are called bounded context.</p><h3>The architecture in practice</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*ZSlL0m8jSjYi6xWX4nvb0g.gif" /></figure><p>As an example, I choose the demo app used by <a href="https://medium.com/u/81022b7454b7">Dane Mackier</a> in his tutorials. The app has three screens. <strong><em>Login</em></strong>, <strong><em>Home </em></strong>and <strong><em>PostDetails</em></strong>.It communicates with the <a href="https://jsonplaceholder.typicode.com/">JSONPlaceholder API</a>, gets a <strong><em>User </em></strong>profile from the login using the ID entered. Fetches and shows the <strong><em>Posts </em></strong>on the home view and shows post details with an additional fetch to show the comments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/252/1*cSOTUa8o39K3cA-_U9KhOQ.gif" /></figure><h4>I. Domain</h4><p><strong>I.1 entities :</strong></p><p>There are three entities: <strong><em>User</em></strong>, <strong><em>Post</em></strong>, and <strong><em>Comment</em></strong>.</p><p><strong><em>file:lib/domain/entities/user.dart</em></strong></p><pre>class User {<br>  <strong>int id; </strong><br>  String name;<br>  String username;</pre><pre><strong>//Typically called form service layer to create a new user</strong><br>  User({this.id, this.name, this.username});</pre><pre><strong>//Typically called from the data_source layer after getting data from an external source.</strong><br>  User.fromJson(Map&lt;String, dynamic&gt; json) {<br>    id = json[&#39;id&#39;];<br>    name = json[&#39;name&#39;];<br>    username = json[&#39;username&#39;];<br>  }</pre><pre><strong>//Typically called from service or data_source layer just before persisting data.</strong><br>  <strong>//Here is the appropriate place to check data validity before persistence.</strong><br>  Map&lt;String, dynamic&gt; toJson() {<br>    <strong>//validate<br>    _validation();</strong><br>    final Map&lt;String, dynamic&gt; data = new Map&lt;String, dynamic&gt;();<br>    data[&#39;id&#39;] = this.id;<br>    data[&#39;name&#39;] = this.name;<br>    data[&#39;username&#39;] = this.username;<br>    return data;<br>  }</pre><pre>_validation() {<br>    if (name == null) {<br>      <strong>//NullNameException is defined in the exception folder of the domain</strong><br>      throw NullNameException();<br>    }<br>  }<br>}</pre><p><strong><em>file:lib/domain/entities/post.dart</em></strong></p><pre>class Post {<br>  int id;<br>  int userId;<br>  String title;<br>  String body;<br>  int likes;</pre><pre>Post({this.id, this.userId, this.title, this.body, this.likes});</pre><pre>Post.fromJson(Map&lt;String, dynamic&gt; json) {<br>    userId = json[&#39;userId&#39;];<br>    id = json[&#39;id&#39;];<br>    title = json[&#39;title&#39;];<br>    body = json[&#39;body&#39;];<br>    likes = 0;<br>  }</pre><pre>Map&lt;String, dynamic&gt; toJson() {<br>    _validation();<br>    final Map&lt;String, dynamic&gt; data = new Map&lt;String, dynamic&gt;();<br>    data[&#39;userId&#39;] = this.userId;<br>    data[&#39;id&#39;] = this.id;<br>    data[&#39;title&#39;] = this.title;<br>    data[&#39;body&#39;] = this.body;<br>    data[&#39;likes&#39;] = this.likes;<br>    return data;<br>  }</pre><pre><strong>//Entities should contain all the logic it controls<br>  incrementLikes() {<br>    likes++;<br>  }</strong></pre><pre>_validation() {<br>    if (userId == null) {<br>      throw ValidationException(&#39;User id can not be undefined&#39;);<br>    }<br>  }<br>}</pre><p><strong><em>file:lib/domain/entities/comment.dart</em></strong></p><pre>class Comment {<br>  int id;<br>  int postId;<br>  String name;<br><strong>  //Email is a value object<br>  Email email;</strong><br>  String body;</pre><pre>Comment({this.id, this.postId, this.name, this.email, this.body});</pre><pre>Comment.fromJson(Map&lt;String, dynamic&gt; json) {<br>    postId = json[&#39;postId&#39;];<br>    id = json[&#39;id&#39;];<br>    name = json[&#39;name&#39;];<br>    email = Email(json[&#39;email&#39;]);<br>    body = json[&#39;body&#39;];<br>  }</pre><pre>Map&lt;String, dynamic&gt; toJson() {<br>    _validation();<br>    final Map&lt;String, dynamic&gt; data = new Map&lt;String, dynamic&gt;();<br>    data[&#39;postId&#39;] = this.postId;<br>    data[&#39;id&#39;] = this.id;<br>    data[&#39;name&#39;] = this.name;<br>    data[&#39;email&#39;] = this.email.email;<br>    data[&#39;body&#39;] = this.body;<br>    return data;<br>  }</pre><pre>_validation() {<br>    if (postId == null) {<br>      throw ValidationException(&#39;No post is associated with this comment&#39;);<br>    }<br>  }<br>}</pre><p><strong>I.2 value_objects:</strong></p><p>For a demonstration purposes, I refactor the email field to be value_object class.</p><p><strong><em>file:lib/domain/value_objects/email.dart</em></strong></p><pre>//value objects are immutable<br><a href="http://twitter.com/immutable"><strong>@immutable</strong></a><br>class Email {<br>  Email(this.email) {<br><strong>    if (!email.contains(&#39;@&#39;)) {<br>      //Validation at the time of construction<br>      throw ValidationException(&#39;Your email must contain &quot;@&quot;&#39;);<br>    }</strong><br>  }</pre><pre>final String  email;<br>}</pre><blockquote>Entities are validated just before persistence whereas value_objects are validated the time of instantiation</blockquote><p><strong>I.3 exceptions:</strong></p><p><strong><em>file:lib/domain/exceptions/validation_exception.dart</em></strong></p><pre>class ValidationException extends Error {<br>  ValidationException(this.message);<br>  final String message;<br>}</pre><p>The domain layer is complete. It is the most independent part of the application and reflects the enterprise-wide application logic.</p><h4>II. service</h4><p><strong>II.1 interfaces:</strong></p><p><strong><em>file:lib/service/interfaces/i_api.dart</em></strong></p><pre>abstract class IApi {<br>  Future&lt;User&gt; <strong>getUserProfile</strong>(int userId);<br>  Future&lt;List&lt;Post&gt;&gt; <strong>getPostsForUser</strong>(int userId);<br>  Future&lt;List&lt;Comment&gt;&gt; <strong>getCommentsForPost</strong>(int postId);<br>}</pre><p>The data_source layer part must implement this interface.</p><p><strong>II.2 exceptions:</strong></p><p><strong><em>file:lib/exceptions/input_exception.dart</em></strong></p><pre>class <strong>NotNumberException </strong>extends Error {<br>  final message = &#39;The entered value is not a number&#39;;<br>}</pre><p><strong><em>file:lib/exceptions/</em>fetch_exception<em>.dart</em></strong></p><pre>class <strong>NetworkErrorException </strong>extends Error {<br>  final message = &#39;A NetWork problem&#39;;<br>}</pre><pre>class <strong>UserNotFoundException </strong>extends Error {<br>  UserNotFoundException(this._userID);<br>  final int _userID;<br>  String get message =&gt; &#39;No user find with this number $_userID&#39;;<br>}</pre><pre>class <strong>PostNotFoundException </strong>extends Error {<br>  PostNotFoundException(this._userID);<br>  final int _userID;<br>  String get message =&gt; &#39;No post fount of user with id:  $_userID&#39;;<br>}</pre><pre>class <strong>CommentNotFoundException </strong>extends Error {<br>  CommentNotFoundException(this._postID);<br>  final int _postID;<br>  String get message =&gt; &#39;No comment fount of post with id:  $_postID&#39;;<br>}</pre><p><strong>II.3 common:</strong></p><p>the common folder will contain one helper file to parser input string to integer and validate it.</p><p><strong><em>file:lib/common/input_parser.dart</em></strong></p><pre>class <strong>InputParser </strong>{<br>  static int <strong>parse</strong>(String userIdText) {<br>    var userId = int.tryParse(userIdText);<br>    if (userId == null) {<br>      throw NotNumberException();<br>    }<br>    return userId;<br>  }<br>}</pre><p>Typically and not necessary, for each entity, there is a corresponding service class that is responsible for its instantiation and its persistence by delegating to external services. These service classes are also responsible for processing the entities and value objects so that they are suitable for use cases.</p><p>In our app, we have three service classes: <strong><em>AuthenticationService</em></strong>, <strong><em>PostsService</em></strong>, <strong><em>CommentsService</em></strong>.</p><p>In the root of the service class:</p><p><strong>file:lib/service/authentication_service.dart</strong></p><pre>class <strong>AuthenticationService </strong>{<br>  AuthenticationService({IApi api}) : _api = api;<br>  IApi _api;<br>  User _fetchedUser;<br>  User get user =&gt; _fetchedUser;</pre><pre>void <strong>login</strong>(String userIdText) async {<br>    <strong>//Delegate the input parsing and validation</strong><br>    var userId = InputParser.parse(userIdText);</pre><pre>_fetchedUser = await _api.getUserProfile(userId);</pre><pre>//// TODO1 : throw unhandled exception</pre><pre>////TODO2: Instantiate a value object in a bad state.</pre><pre>////TODO3: try to persist an entity is bad state.</pre><pre>}<br>}</pre><p><strong><em>AuthenticationService </em></strong>is responsible for fetching for user form input id and caching the obtained user in memory (the getter user).</p><p>There are three TODOs that we will fill out later at the end of the article to see how the application behaves when throwing unhandled exceptions, instantiating a value object in a bad state and finally the persisting of an entity in a bad state.</p><p><strong><em>file:lib/service/posts_service.dart</em></strong></p><pre>class PostsService {<br>  PostsService({IApi api}) : _api = api;<br>  IApi _api;<br>  List&lt;Post&gt; _posts;<br>  List&lt;Post&gt; get <strong>posts </strong>=&gt; _posts;</pre><pre>void <strong>getPostsForUser</strong>(int userId) async {<br>    _posts = await _api.getPostsForUser(userId);<br>  }</pre><pre><strong>//Encapsulation of the logic of getting post likes.<br></strong>  int <strong>getPostLikes</strong>(postId) {<br>    return _posts.firstWhere((post) =&gt; post.id == postId).likes;<br>  }</pre><pre><strong>//Encapsulation of the logic of incrementing the like of a post.<br></strong>  void <strong>incrementLikes</strong>(int postId) {<br>    _posts.firstWhere((post) =&gt; post.id == postId).incrementLikes();<br>  }<br>}</pre><p><strong><em>file:lib/service/comments_service.dart</em></strong></p><pre>class CommentsService {<br>  IApi _api;<br>  CommentsService({IApi api}) : _api = api;</pre><pre>List&lt;Comment&gt; _comments;<br>  List&lt;Comment&gt; get <strong>comments </strong>=&gt; _comments;</pre><pre>Future&lt;void&gt; <strong>fetchComments</strong>(int postId) async {<br>    _comments = await _api.getCommentsForPost(postId);<br>  }<br>}</pre><p>And we’ve done with the service layer and all the business logic of our app.</p><h4>III. data_source</h4><p><strong><em>file:lib/</em></strong>data_source<strong><em>/api.dart</em></strong></p><pre><strong>class Api implements IApi</strong> {<br>  static const endpoint = &#39;<a href="https://jsonplaceholder.typicode.com&/#39;">https://jsonplaceholder.typicode.com&#39;</a>;</pre><pre>var client = new http.Client();</pre><pre>Future&lt;User&gt; <strong>getUserProfile</strong>(int userId) async {<br>    var response;<br>    try {<br>      response = await client.get(&#39;$endpoint/users/$userId&#39;);<br>    } catch (e) {<br>      //Handle network error<br>      //It must throw custom errors classes defined in the service layer<br>      throw <strong>NetworkErrorException</strong>();<br>    }</pre><pre>//Handle not found page<br>    if (response.statusCode == 404) {<br>      throw UserNotFoundException(userId);<br>    }</pre><pre>return User.fromJson(json.decode(response.body));<br>  }</pre><pre>Future&lt;List&lt;Post&gt;&gt; <strong>getPostsForUser</strong>(int userId) async {<br>    var posts = List&lt;Post&gt;();<br>    var response;<br>    try {<br>      response = await client.get(&#39;$endpoint/posts?userId=$userId&#39;);<br>    } catch (e) {<br>      throw NetworkErrorException();<br>    }<br>    if (response.statusCode == 404) {<br>      throw PostNotFoundException(userId);<br>    }</pre><pre>var parsed = json.decode(response.body) as List&lt;dynamic&gt;;</pre><pre>for (var post in parsed) {<br>      posts.add(Post.fromJson(post));<br>    }</pre><pre>return posts;<br>  }</pre><pre>Future&lt;List&lt;Comment&gt;&gt; <strong>getCommentsForPost</strong>(int postId) async {<br>    var comments = List&lt;Comment&gt;();</pre><pre>var response;<br>    try {<br>      response = await client.get(&#39;$endpoint/comments?postId=$postId&#39;);<br>    } catch (e) {<br>      throw NetworkErrorException();<br>    }<br>    if (response.statusCode == 404) {<br>      throw CommentNotFoundException(postId);<br>    }</pre><pre>var parsed = json.decode(response.body) as List&lt;dynamic&gt;;</pre><pre>for (var comment in parsed) {<br>      comments.add(Comment.fromJson(comment));<br>    }</pre><pre>return comments;<br>  }<br>}</pre><p>The <strong><em>Api </em></strong>class <strong>implements</strong> the <strong><em>IApi </em></strong>class form the interface folder of the service layer. Errors must be catches and custom error defined in the service layer must be thrown instead.</p><h4>IV. infrastructure</h4><p>Not needed in this example. It can have external libraries that deal with platform-specific tasks such as check for network connection, use GPS, use email service ….</p><h4>V. User Interface UI</h4><p>As you saw, the domain, service, data_source, and infrastructure layers are constituted with plain old dart classes and have nothing to do with <strong><em>states_rebuilder</em></strong>.</p><p>It is in the UI that we need to use<strong> states_rebuilder</strong> and it is important to read the <a href="https://medium.com/@meltft/states-rebuilder-and-animator-articles-4b178a09cdfa?source=your_stories_page---------------------------">last articles</a> on states_rebuilder and watch <a href="https://resocoder.com/2019/12/30/states-rebuilder-zero-boilerplate-flutter-state-management/"><strong>ResoCoder </strong></a>tutorial to be able to follow with me the next couple of lines:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FiIxWMeFnIKA%3Ffeature%3Doembed&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DiIxWMeFnIKA&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FiIxWMeFnIKA%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/b65e5e602b1231fa6507c332e16c335c/href">https://medium.com/media/b65e5e602b1231fa6507c332e16c335c/href</a></iframe><p><strong><em>file:lib/main.dart</em></strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/38a225b914b875ea8ecaed458833989d/href">https://medium.com/media/38a225b914b875ea8ecaed458833989d/href</a></iframe><p>Because we need the authenticated user to be available throughout all the widget tree we inject it before the <strong><em>MaterialApp </em></strong>widget.</p><p>The first page is the login page:</p><p><strong><em>file:lib/pages/login_page/login_page.dart</em></strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5cd0a513e0ec7f28680bc492fb4734cb/href">https://medium.com/media/5cd0a513e0ec7f28680bc492fb4734cb/href</a></iframe><p>I would like to emphasize that error handling is centralized in <strong><em>ErrorHandler </em></strong>class which will be in the common folder of the UI layer.</p><p>If the user is successfully authenticated we navigate to the home page</p><p><strong><em>file:lib/pages/home_page/home_page.dart</em></strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d804f1e0b124dc048940df353ccdfe5e/href">https://medium.com/media/d804f1e0b124dc048940df353ccdfe5e/href</a></iframe><p>From this moment, the user is available and to get it we can simply by using <strong><em>Injector.get, </em></strong>because we no longer need it to be reactive.</p><pre>final user = <strong>Injector.get</strong>&lt;AuthenticationService&gt;().user;</pre><blockquote>With states_rebuilder, you always have the choice of getting an injected model using <strong><em>Injector.get</em></strong> and <strong><em>Injector.getAsReactive</em></strong>. Unless you need reactivity, prefer <strong>Injector.get</strong></blockquote><p>The <strong><em>postsService </em></strong>class is injected inside the <strong><em>homePage </em></strong>widget. If you navigate to the next page using <strong><em>pushReplacementNamed </em></strong>(or <strong><em>pushReplacement</em></strong>) the <strong><em>homePage </em></strong>will be disposed and the <strong><em>postsService </em></strong>will be unregistered. If you want to keep using the injected instance of <strong><em>postsService </em></strong>on the next page, you reinject it with the help of the <strong><em>reinject </em></strong>parameter of the <strong><em>Injector</em></strong>:</p><p>for our case, in the <strong><em>lib/router.dart</em></strong> file replace</p><pre>case ‘post’:<br>var post = settings.arguments as Post;<br>return MaterialPageRoute(builder: (_) =&gt; <strong>PostPage(post: post)</strong>);</pre><p>by</p><pre>case ‘post’:<br>var post = settings.arguments as Post;<br>return MaterialPageRoute(builder: (_) =&gt; <strong>Injector(<br>    reinject: [Injector.getAsReactive&lt;PostsService&gt;()],<br>    builder: (context) { <br>      return PostPage(post: post));<br>   },</strong><br>);</pre><p><strong><em>file:lib/pages/post_page/post_page.dart (entry file)</em></strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f59882904ab281c5402e159f2088560/href">https://medium.com/media/7f59882904ab281c5402e159f2088560/href</a></iframe><p>We put the <strong><em>like_button.dart</em></strong> and<strong><em> comments.dart</em></strong> file inside the post_page folder and not in the widgets folder because they depend on the service and domain layer and are not used by other pages. For me, the widgets folder is reserved for small, reusable and app independent widgets.</p><p><strong><em>file:lib/pages/post_page/like_button.dart</em></strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/13637989f3b186feaa53899663a05d40/href">https://medium.com/media/13637989f3b186feaa53899663a05d40/href</a></iframe><p><strong><em>file:lib/pages/post_page/comments.dart</em></strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e90b2f421fe5371d08202094ea5bdd56/href">https://medium.com/media/e90b2f421fe5371d08202094ea5bdd56/href</a></iframe><p>It remains to us the <strong><em>ErrorHandler </em></strong>class.</p><p><strong><em>file:lib/pages/exceptions/error_handler.dart</em></strong></p><pre>class ErrorHandler {<br>  <strong>//go through all custom errors and return the corresponding error message</strong><br>  <strong>static String errorMessage(dynamic error)</strong> {<br>    if (error == null) {<br>      return null;<br>    }<br>    if (error is ValidationException) {<br>      return error.message;<br>    }</pre><pre>if (error is NotNumberException) {<br>      return error.message;<br>    }</pre><pre>if (error is NetworkErrorException) {<br>      return error.message;<br>    }</pre><pre>if (error is UserNotFoundException) {<br>      return error.message;<br>    }</pre><pre>if (error is PostNotFoundException) {<br>      return error.message;<br>    }</pre><pre>if (error is CommentNotFoundException) {<br>      return error.message;<br>    }<br>    <strong>// throw unexpected error.</strong><br>    throw error;<br>  }</pre><pre><strong>//Display an AlertDialog with the error message</strong><br>  <strong>static void showErrorDialog(BuildContext context, dynamic error)</strong> {<br>    if (error == null) {<br>      return;<br>    }<br>    showDialog(<br>      context: context,<br>      builder: (context) {<br>        return AlertDialog(<br>          content: Text(errorMessage(error)),<br>        );<br>      },<br>    );<br>  }<br>}</pre><p>The error handling logic is centralized in <strong><em>ErrorHandler.</em></strong></p><ul><li>Whenever we want to display an error message we use <strong><em>ErrorHandler.</em>errorMessage(error).</strong></li></ul><pre>LoginHeader(<br> <strong>ErrorHandler.errorMessage(authServiceRM.error),</strong><br> controller: controller,<br>),</pre><ul><li>Whenever we want to display a side effect AlertDialog we use <strong><em>ErrorHandler.</em>errorMessage(error) with the onError parameter of setState:</strong></li></ul><pre>postsServiceRM.setState(<br>  (state) =&gt; state.getPostsForUser(user.id),<br>   <strong>onError: ErrorHandler.showErrorDialog,</strong><br>);</pre><p>That’s it; pure dart business logic classes, simple UI widgets, and many other features about managing the stats, DI and app lifecycle not mentioned here you can read about it in the official documentation.</p><h4>Some changes:</h4><blockquote>Good app architecture makes changes easier with fewer side effects.</blockquote><p>If you notice in the GIF, if I enter a number greater than 10, the app fetches for it and get a 404 error, and displays an error saying that no user found with the entered number.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/252/1*cSOTUa8o39K3cA-_U9KhOQ.gif" /></figure><p>A good practice is to catch an error as early as it appears. For this good reason, I have to validate input and prevent fetching non-existing numbers.</p><p>To do so, with this architecture we simply change the following files:</p><p><strong><em>file:lib/common/input_parser.dar</em></strong></p><p>throw <strong><em>NotInRangeException</em></strong><em> </em>if userID is less than one or greater than 10</p><pre>class <strong>InputParser </strong>{<br>  static int <strong>parse</strong>(String userIdText) {<br>    var userId = int.tryParse(userIdText);<br>    if (userId == null) {<br>      throw NotNumberException();<br>    }<br>    <br>   <strong> if (userId &lt; 1 || userId &gt; 10) {<br>       throw NotInRangeException();<br>     }</strong></pre><pre>return userId;<br>  }<br>}</pre><p><strong><em>file:lib/exceptions/input_exception.dart</em></strong></p><p>Add <strong><em>NotInRangeException </em></strong>exceptions.</p><pre>class NotNumberException extends Error {<br>  final message = &#39;The entered value is not a number&#39;;<br>}</pre><pre><strong>class NotInRangeException extends Error {<br>  final message = &#39;Tne entered value is not between 1 and 10&#39;;<br>}</strong></pre><p>and handle it:</p><p><strong><em>file:lib/pages/exceptions/error_handler.dart</em></strong></p><pre>class ErrorHandler {<br> static String errorMessage(dynamic error) {<br>    ..<br>    <strong>if (error is NotInRangeException) {<br>       return error.message;<br>    }</strong><br>    ..<br>  }<br>}</pre><p>That all to get what you want:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/252/1*GOjbkqhJ8lUd6_inuJwr5w.gif" /></figure><p>What if I want to show a snackBar containing the error.</p><blockquote>With <strong>states_rebuilder</strong>, error handling and side effect management are a joy.</blockquote><p>At the end of <strong><em>file:lib/pages/exceptions/error_handler.dart, </em></strong>we add:</p><pre>class ErrorHandler {<br> static String errorMessage(dynamic error) {<br>   ..<br>  //Display an snackBar with the error message<br> <strong> static void showSnackBar(BuildContext context, dynamic error) {<br>    if (error == null) {<br>      return;<br>    }<br>    Scaffold.of(context).showSnackBar(<br>      SnackBar(<br>        content: Text(&#39;${errorMessage(error)}&#39;),<br>      ),<br>    );<br>  }</strong><br>  ..<br> }<br>}</pre><p>in the <strong><em>file:lib/pages/login_page/login_page.dart </em></strong>and in onPressed callback we add:</p><pre>onPressed: () {</pre><pre>authServiceRM.setState(<br>   (state) =&gt; state.login(controller.text),<br>    <strong>onError: ErrorHandler.showSnackBar,</strong><br>    onData: (context, authServiceRM) {<br>      Navigator.pushNamed(context, &#39;/&#39;);<br>    },<br>  );<br>},</pre><p>And that all to get what we want:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/252/1*wA0xgCa7i91KXggxbEIpBw.gif" /></figure><h4>Some TODOS:</h4><p>In <strong>file:lib/service/authentication_service.dart, </strong>we left with some TODOS to check validation functionallity of states_rebuilder.</p><pre>class <strong>AuthenticationService </strong>{<br>  AuthenticationService({IApi api}) : _api = api;<br>  IApi _api;<br>  User _fetchedUser;<br>  User get user =&gt; _fetchedUser;</pre><pre>void <strong>login</strong>(String userIdText) async {<br>    <strong>//Delegate the input parsing and validation</strong><br>    var userId = InputParser.parse(userIdText);</pre><pre>_fetchedUser = await _api.getUserProfile(userId);</pre><pre>//// TODO1 : throw unhandled exception</pre><pre>////TODO2: Instantiate a value object in a bad state.</pre><pre>////TODO3: try to persist an entity is bad state.</pre><pre>}<br>}</pre><ul><li>The first TODO is to throw an unexpected exception:</li></ul><pre>//// TODO1 : throw unhandled exception<br><strong>throw Exception();</strong></pre><p>When you click the login button the app will crash.</p><ul><li>The second TODO is to try instantiating the Email value object in a non-valid state:</li></ul><pre>////TODO2: Instantiate a value object in a bad state.<br>Comment(<br> id: 1,<br> <strong>email: Email(&#39;email.com&#39;), //Bad email</strong><br> name: &#39;Joe&#39;,<br> body: &#39;comment&#39;,<br>  postId: 2,<br>);</pre><p>When you click the login button the red validation message will appear.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/252/1*OcQ3567-lCwBqvHHqWhMvA.gif" /></figure><ul><li>The last TODO is to try to persist an entity is a bad state.</li></ul><pre>////TODO3: try to persist an entity is bad state.<br>Comment(<br> id: 1,<br> <strong>email: Email(&#39;email@m.com&#39;), //good email</strong><br> name: &#39;Joe&#39;,<br> body: &#39;comment&#39;,<br> postId: 2,<br>)<br><strong>..postId = null// bad state</strong><br>..toJson();</pre><p>When you click the login button the validation message telling you that you can not persist a comment with not postID.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/252/1*-J1eE8fYBaQ6pfC69yJn7Q.gif" /></figure><p>You can find the code of this article and many other tutorials <a href="https://github.com/GIfatahTH/states-rebuilder-examples">here</a>.</p><p>Now <strong><em>states_rebuilder </em></strong>is part of the<strong><em> </em>TodoMVC</strong> for Flutter samples. Check <a href="https://github.com/brianegan/flutter_architecture_samples">flutter_architecture_samples </a>and see how the same app is implemented by many state management solutions.</p><p>Please try the library, star ⭐️ it in the <a href="https://github.com/GIfatahTH">GitHub</a>, give it a thumb up 👍 in the <a href="https://pub.dev/packages/states_rebuilder">pub.dev</a> and clap 👏 and share 👭 this article.</p><ul><li><a href="https://pub.dev/packages/states_rebuilder">states_rebuilder | Flutter Package</a></li><li><a href="https://www.twitter.com/FlutterComm">JavaScript is not available.</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c9b91c3b9b6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/flutter-community/clean-architecture-with-states-rebuilder-has-never-been-cleaner-6c9b91c3b9b6">Clean Architecture with states_rebuilder has Never Been Cleaner</a> was originally published in <a href="https://medium.com/flutter-community">Flutter Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[State Management Gymnastics using states_rebuilder. Part 2.]]></title>
            <link>https://medium.com/flutter-community/state-management-gymnastics-using-states-rebuilder-part-2-a7fa0dd7dc51?source=rss-818757b53c98------2</link>
            <guid isPermaLink="false">https://medium.com/p/a7fa0dd7dc51</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[MELLATI Fatah]]></dc:creator>
            <pubDate>Fri, 03 Jan 2020 16:26:39 GMT</pubDate>
            <atom:updated>2020-01-03T16:26:39.205Z</atom:updated>
            <content:encoded><![CDATA[<p>This is the second part of a series of articles that aims to show the functionality of the states_rebuilder library by creating an application that has quite complex state management requirements.</p><p>It is mandatory to read the first article before continuing reading this article (<a href="https://medium.com/flutter-community/state-management-gymnastics-using-states-rebuilder-part-1-3ba3a6abf9c7">link here</a>).</p><p><strong>What makes states_rebuilder different:</strong></p><blockquote>Write your business logic using pure dart classes and reactivity is implicitly added for you, in a way that gives you full control over which part of the widget tree to rebuild and when to notify it.</blockquote><p>1. With <strong><em>states_rebuilder </em></strong>you can achieve a clear separation between UI and business logic;</p><p>2. Your business logic is made up of pure dart classes without the need to refer to external packages or frameworks (NO extension, NO notification, NO annotation);</p><pre>class Foo {<br> //Vanilla dart class<br> //NO inheritance form external libraries<br> //NO notification<br> //No annotation<br>}</pre><p>3. You make a singleton of your logical class available to the widget tree by injecting it using the <strong><em>Injector </em></strong>widget.</p><pre>Injector(<br> inject : [Inject(()=&gt;Foo())]<br> builder : (context) =&gt; MyChildWidget()<br>)</pre><p>4. From any child widget of the <strong><em>Injector </em></strong>widget, you can get the registered raw singleton using the static method <strong><em>Injector.get&lt;T&gt;() </em></strong>method;</p><pre>final Foo foo = Injector.get&lt;Foo&gt;();</pre><p>5. To get the registered singleton wrapped with a reactive environment, you use the static method <strong><em>Injectro.getAsReactive&lt;T&gt;()</em> </strong>method:</p><pre>final ReactiveModel&lt;Foo&gt; foo = Injector.getAsReactive&lt;Foo&gt;();</pre><p>In fact, for each injected model, <strong><em>states_rebuilder </em></strong>registers two singletons:<br>- The raw singleton of the model<br>- The reactive singleton of the model which is the raw singleton wrapped with a reactive environment:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/405/1*euYYiiE-m8pUKk_cHj75Eg.png" /></figure><p>The reactive environment adds getters, fields, and methods to modify the state, follow the state of the reactive environment and notify the widgets which are subscribed to it.</p><p>In the last article we saw the following getters: <strong>state</strong>, <strong>connectionState</strong>, <strong>hasError</strong>, <strong>error </strong>and the <strong>setState </strong>method.</p><p>6. The <strong>setState </strong>method is where actions that mutate the state and send notifications are defined:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*48J2YBmDg-fisdGGpCgzxQ.png" /></figure><p>What happens is that from the user interface, we use the <strong><em>setState </em></strong>method to mutate the state and notify subscribed widgets after the state mutation. In the <strong><em>setState</em></strong>, we can define a callback for all the side effects to be executed after the state change and just before rebuilding subscribed widgets using <strong><em>onSetState </em></strong>parameter(or <strong><em>onRebuild </em></strong>so that the code executes after the reconstruction). From inside <strong><em>onSetState</em></strong>, we can call another <strong><em>setState </em></strong>to mutate the state and notify the user interface with another call <strong><em>onSetState </em></strong>(<strong><em>onRebuild</em></strong>) and so on …</p><p>The following picture sketches the trigger-mutate-notify-side effects process:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/1*fv46zfbBHk5gMdzL42suHw.png" /></figure><p>In the <a href="https://medium.com/flutter-community/state-management-gymnastics-using-states-rebuilder-part-1-3ba3a6abf9c7">last article</a>, we started from this pure dart class :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TXnRaNt0TElqjpbTQW79_g.png" /></figure><p>and built this simple counter app that shows a <strong><em>CircularProgressIndicator </em></strong>while waiting for an asynchronous task to finished and increment a counter with the possibility of throwing an error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*1W-wlXyIKIqUe3Jgrc10-Q.gif" /></figure><p>In this article, we want to start from the same <strong><em>FutureWithCounter </em></strong>model and create an application with tricky state management requirements:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/354/1*SU6J_2TZWtP0YcvYzzxraw.png" /><figcaption>The UI of the app to build</figcaption></figure><ol><li>The app has <strong><em>Scaffold </em></strong>with an <strong><em>AppBar </em></strong>and its body contains four quarters (counters); each within its own <strong><em>Scaffold</em></strong>.</li><li>We want each quarter (counter) to be independent (although they use the same instance of the <strong><em>FutureWithCounter </em></strong>model).</li><li>If a quarter (counter) has an error, we want its own <strong><em>AppBar </em></strong>to be red and we want to show a <strong><em>SnackBar </em></strong>containing the error message (counter 2 in the above picture);</li><li>We want the app’s AppBar to display the name of the counter that was tapped with its status (<strong><em>CircularProgressIndicator </em></strong>if waiting);</li><li>We want the app’s AppBar<strong> </strong>to display a red error message if at least one counter has an error.</li><li>If all counters are incremented and none of them has an error, we want the app’s AppBar<strong> </strong>to display a message successful message.</li></ol><p>Here is the final GIF we want to get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/252/1*Vvo54_NrPRnz73vRZMVIcg.gif" /></figure><p>I want to emphasize that these state management requirements must be met using a simple pure dart model:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/468fb1fc4fdf572ba97c4e6dc3509b53/href">https://medium.com/media/468fb1fc4fdf572ba97c4e6dc3509b53/href</a></iframe><p>The <strong><em>FutureCounterWithError </em></strong>is the model, BloC, service or whatever you want to call. It is a vanilla dart class without any framework or library dependence.</p><p>As mentioned in the last article, any state management library must first provide (or inject) a single instance of the model in the widget tree and make it accessible to child widgets.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ac928fafa5684293816dc9314893fc2f/href">https://medium.com/media/ac928fafa5684293816dc9314893fc2f/href</a></iframe><p>NOTE 1: We inject the <strong><em>FutureCounterWithError </em></strong>class in the constructor of the Inject class.<br>NOTE 2: We get the reactive singleton of the injected model without the <strong><em>context </em></strong>parameter because we don’t want to subscribe the <strong><em>BuildContext </em></strong>to the reactive model.<br>NOTE 3: <strong><em>CounterWidget </em></strong>is a custom Widget that we defined to be reusable :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dd97d67ba01688f77a22f7f93763d38d/href">https://medium.com/media/dd97d67ba01688f77a22f7f93763d38d/href</a></iframe><p>As required by the state management requirements, we want the local <strong><em>AppBar </em></strong>for each counter to be red if the model has an error. For this reason, we wrapped the <strong><em>Theme </em></strong>widget with a <strong><em>StateBuilder </em></strong>widget.</p><p>NOTE 1: We used the <strong><em>StateBuilder </em></strong>widget to subscribe to the <strong><em>counterModel</em></strong>. This <strong><em>StateBuilder </em></strong>is subscribed with two tags so that each time the <strong><em>counterModel </em></strong>emits a notification with at least one of these tags, this <strong><em>StateBuilder </em></strong>will be notified to rebuild.</p><p>NOTE 2: Because we want to change the theme without rebuilding the entire scaffold, we use the <strong><em>builderWithChild </em></strong>parameter instead of the <strong><em>builder </em></strong>parameter. What is inside the <strong><em>builderWithChild </em></strong>will be rebuilt and what is held with the <strong><em>child </em></strong>parameter will not rebuild.</p><p>with <strong><em>states_rebuilder</em></strong>, you have to define either <strong><em>builder </em></strong>or <strong><em>builderWithChilde </em></strong>parameter:</p><pre>StateBuilder&lt;T&gt;(<br> <strong>builder </strong>: (BuildContext context, ReactiveModel&lt;T&gt; model){<br>  return WidgetToRebuild()<br> }<br>)</pre><pre>//OR<br>StateBuilder&lt;T&gt;(<br> <strong>builderWithChild </strong>: (BuildContext context, ReactiveModel&lt;T&gt; model, Widget child){<br>  return WidgetToRebuild(child: child)<br> }<br> <strong>child</strong>: WidgetNotToRebuild()<br>)</pre><p>NOTE 3: call <strong><em>setState </em></strong>Method to mutate the state and notify subscribed widgets with the provided <strong><em>tagFilter </em></strong>list.</p><p>NOTE 4: define the <strong><em>onError </em></strong>callback that will be called whenever a notification is sent with an error.</p><pre>onError(BuildContext context, dynamic error){<br> // side effect code<br>}</pre><p><strong><em>onError </em></strong>is a shortcut to :</p><pre>catchError : true;<br>onSetState(BuildContext context){<br> if (reactiveModel.hasError){<br>  //side Effect code<br> }<br>}</pre><p>NOTE 5: <strong><em>CounterApp </em></strong>is a widget that displays the value of the counters. If you followed the first part, you won’t find anything special:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/421b97212e56c50d86dd390dfe1e3493/href">https://medium.com/media/421b97212e56c50d86dd390dfe1e3493/href</a></iframe><p>This is the resultant GIF:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/252/1*oim57R-oLJWdTn2JpRl2xA.gif" /></figure><p>َAs you see in the GIF, this is not the behavior we want. Each time the state of a counter changes, the state of all other counters changes. Also, note the snackBar, it appears in counter 4 while the error comes from counter 1 and it is far from what the state management requirements impose.</p><p>In fact, this behavior is expected because the four counters share the same reactive environment. If one of them changes the status of the reactive environment, the other counters will be affected because they are surrounded by the same reactive environment.</p><p>To fill this gap, we must ensure that each counter has an independent reactive environment.</p><p>As we said, <strong><em>states_rebuilder </em></strong>caches two singletons (the raw singleton and the reactive singleton). Besides these two singletons, with <strong><em>states_rebuilder</em></strong>, you can create as many new reactive environments as you want.</p><blockquote>New reactive instance is the same raw singleton decorated with a new reactive environment</blockquote><p>The following picture shows how reactive instances interact:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/657/1*H7cPVgN4oSJGk9wsgwOQVg.png" /></figure><p>The reactive singleton and reactive instances share the same raw singleton of the model. Each of them can invoke its own <strong><em>setState</em></strong>, change its own state and notify widgets that have already subscribed to it.</p><blockquote>The idea is simple, you use pure dart classes and <strong><em>states_rebuilder </em></strong>adds reactivity by decorating them with a reactive environment. For each model, you can get many reactive instances.</blockquote><p>To create a new reactive instance of an injected model use:</p><p>1- <strong><em>Injector.getAsReactive </em></strong>with the parameter <strong><em>asNewReactiveInstance </em></strong>equals true</p><pre>ReactiveModel&lt;T&gt; model = Injector.getAsReactive&lt;T&gt;(asNewReactiveInstance: true);</pre><p>2- <strong><em>StateBuilder </em></strong>with generic type and without <strong><em>models </em></strong>property.</p><pre>StateBuilder&lt;T&gt;(<br>  builder:(BuildContext context, ReactiveModel&lt;T&gt; newReactiveModel){<br>  return YourWidget();<br> }<br>)</pre><p>Let’s refactor the App class with the second approach:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e2789f9b5cbc6f1bc5ce21512905fa11/href">https://medium.com/media/e2789f9b5cbc6f1bc5ce21512905fa11/href</a></iframe><p>I removed the <strong><em>Injector.getAsReactive()</em></strong> line because we do not need it [NOTE1], and I wrapped each <strong><em>CounterWidget </em></strong>with <strong><em>StateBuilder </em></strong>without the <strong><em>models</em></strong><em> </em>parameter and with generic type <strong><em>FutureCounterWithError </em></strong>[NOTE2].</p><p>That all we to do to clean the reactive environment. The new GIF is :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/252/1*Wl7ky8aj2tWDkT7SH0b4Rg.gif" /></figure><p>At this stage, we have met the first, second and third requirements. We still have the last three requirements for the <strong>Appbar </strong>of the application:</p><p>4. We want the application A<strong>ppBar </strong>to display the tapped quarter (counter) name with its status (waiting);<br>5. We want the application <strong>AppBar </strong>to display a red error message if at least one counter has and error.<br>6. If all counter are tried and none of them has an error, we want the application <strong>AppBar </strong>to display a message successful message.</p><p>To achieve this, I will introduce another concept of <strong>states_rebuilder</strong>: ‘The sharing of data and status between a reactive singleton and new reactive instances’.</p><p>With the exception of the raw singleton they share, the reactive singleton and the new reactive instances have an independent reactive environment; BUT:</p><blockquote>New reactive instances can send data to the reactive singleton and share their state status with it.</blockquote><p>If a new reactive instance changes its state and notifies its listeners, we can set it up to share its new state with the reactive singleton and notify the reactive singleton listeners. This can be done in two ways.</p><p>1. The reactive singleton will have the state status of the new reactive instance issuing the notification.</p><pre>Injector(<br> inject: [<br>   Inject(() =&gt; FutureCounterWithError(),<br>   <strong>joinSingleton: JoinSingleton.withNewReactiveInstance,</strong><br>  )<br> ],</pre><pre> builder: (BuildContext context) {<br>  //<br>}<br>)</pre><p>2. The reactive singleton will have a combined state status of all the new reactive instances.</p><pre>Injector(<br> inject: [<br>   Inject(() =&gt; FutureCounterWithError(),<br>   <strong>joinSingleton: JoinSingleton.withCombinedReactiveInstances,</strong><br>  )<br> ],</pre><pre> builder: (BuildContext context) {<br>  //<br> }<br>)</pre><p>In the language of <strong><em>states_rebuilder</em></strong>, we say that we join the reactive singleton with the new reactive instances. The place to define the wiring (joining) is in the <strong><em>Inject </em></strong>class where the model is injected by setting the <strong><em>joinSingleton </em></strong>parameter.</p><p>The combined state status has a similar meaning to that of <strong><em>RxDart </em></strong>for combined streams. The reactive singleton state:<br>1. has an error if at least one of the new reactive instance has error;<br>2. is waiting if at least one of the new reactive instances is waiting;<br>3. is <strong><em>idle </em></strong>if at least one of the new reactive instances is idle;<br>4. has data if all reactive instances have data.</p><p>In addition, a new reactive instance can send custom data to the reactive singleton with the notification. This can be done in the <strong><em>setState </em></strong>method</p><pre>//From a new reactive instance<br>counterModel.setState(<br> (state) =&gt; state.increment(seconds: 1),<br> filterTags: [&#39;blueCounter&#39;],<br><strong> joinSingletonToNewData: &quot;Date to send to reactive singleton&quot;,</strong></pre><pre>)</pre><p><strong>joinSingletonToNewData </strong>takes any type of date.</p><p>For its part, the reactive singleton receives data via its <strong><em>joinSingletonToNewData </em></strong>field</p><pre>//From the reactive singletong</pre><pre>print(counterModelSingleton.<strong>joinSingletonToNewData);</strong></pre><p>Let’s apply these concepts and fulfill the remaining state management requirements</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/19adde7e6348761c2b45d03657b02a3f/href">https://medium.com/media/19adde7e6348761c2b45d03657b02a3f/href</a></iframe><p>NOTE 1 : define <strong>joinSingleton </strong>to be <strong>JoinSingleton.withCombinedReactiveInstances</strong>.</p><p>NOTE 3: Subscribe the reactive singleton with <strong>‘blueCounter’</strong> and <strong>‘greenCounter’</strong> tags using <strong><em>StateBuilder </em></strong>widget. Whenever the reactive singleton emits a notification with one of these tags this <strong><em>StateBuilder </em></strong>will rebuild.</p><p>NOTE 4: Check the status of the reactive singleton and display the corresponding widgets. The reactive singleton holds a combined state of all the new reactive instances as defined above.</p><p>NOTE 5: Display the message sent by the new reactive instance which has just issued the notification. The data sent is kept in the <strong><em>joinSingletonToNewData </em></strong>fields.</p><p>Custom data is emitted from new reactive instances as defined in <strong><em>joinSingletonToNewData </em></strong>parameter of the <strong><em>setState </em></strong>callback:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/daf1e51b593bbda3df118e9343dbb646/href">https://medium.com/media/daf1e51b593bbda3df118e9343dbb646/href</a></iframe><p>This is what state_rebuilder offers you. You write your business logic with pure dart classes without losing control of which part of your widget tree to rebuild and when to rebuild it. Even better with the concept of reactive environments, you can perform very complicated state management tasks that can never be easily done with explicit reactivity as used in <strong><em>ChangeNotifier</em></strong>.</p><p>To see the combined reactive instances in action, see <a href="https://github.com/GIfatahTH/states-rebuilder-examples/tree/master/004-login_form_with_reactive_environnement">this example</a> of a login form with validation and compare it with the way it is done using rxDart and combined streams. (<a href="https://github.com/GIfatahTH/states-rebuilder-examples/tree/master/004-login_form_with_reactive_environnement">link</a>).</p><p>For the code source of this article check this <a href="https://github.com/GIfatahTH/states-rebuilder-examples/tree/master/005-multi_future_counter_with_error">link</a>.</p><p>For a complete list of tutorials visite this <a href="https://github.com/GIfatahTH/states-rebuilder-examples">link</a>.</p><p>Try the <strong><em>states_rebuilder </em></strong>library, give your opinion, report issues and any contribution is welcome.</p><p><a href="https://pub.dev/packages/states_rebuilder">states_rebuilder | Flutter Package</a></p><p>In the next article, I’ll show you how states_rebuilder makes clean architecture even cleaner.</p><p><a href="https://www.twitter.com/FlutterComm">JavaScript is not available.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a7fa0dd7dc51" width="1" height="1" alt=""><hr><p><a href="https://medium.com/flutter-community/state-management-gymnastics-using-states-rebuilder-part-2-a7fa0dd7dc51">State Management Gymnastics using states_rebuilder. Part 2.</a> was originally published in <a href="https://medium.com/flutter-community">Flutter Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[State Management Gymnastics using states_rebuilder. Part 1.]]></title>
            <link>https://medium.com/flutter-community/state-management-gymnastics-using-states-rebuilder-part-1-3ba3a6abf9c7?source=rss-818757b53c98------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ba3a6abf9c7</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[MELLATI Fatah]]></dc:creator>
            <pubDate>Sun, 15 Dec 2019 20:42:45 GMT</pubDate>
            <atom:updated>2020-06-10T21:14:57.219Z</atom:updated>
            <content:encoded><![CDATA[<h3>Flutter State Management Gymnastics Show using states_rebuilder. Part 1.</h3><p>Flutter state management solutions seek to achieve the same goals, but each follows its own path. The ultimate goal is to separate the business logic from the user interface logic.</p><blockquote>The set of business logic objects is what is called the <strong>state</strong>. The user interface in Flutter is created by building a tree of nested widgets. The widget tree reproduces a visual representation of the state, and the state is the ultimate source of truth for the widget tree.</blockquote><p>To achieve such a separation, state management solutions must find a way to:</p><p>1- Inform the widget tree of any state changes so that it rebuilds to reflect the new state. <strong>This is called notifying the widgets.</strong></p><p>2- Make a single instance of the state available to the widget tree and make it accessible to any widget, regardless of how deep it is in the widget tree. <strong>This is called providing or injecting the state.</strong></p><p>One of the most popular packages for managing the state in Flutter is the <strong>provider </strong>package. <strong>provider </strong>uses the observer pattern to notify the widget tree and relies on <strong>InheritedWidget </strong>to provide the state to the widget tree and rebuild the listening widgets. State (model) objects are the observable and <strong>InheritedWidgets </strong>are the observer. The latter register in an observable class and when the state is modified, the observable class notifies the observer InheritedWidgets that transmit the notification to their listening child widgets. Notification is made explicitly by calling <strong>notifyListener()</strong> method.</p><p>Another popular package is <strong>flutter_bloc </strong>that uses streams to notify the widget tree and <strong>InheritedWidget </strong>to provide the state (<strong>BloCs</strong>)<strong>. </strong>In <strong>flutter_bloc</strong>, you must guess all possible states of your widget and all events that will change these states<strong>. </strong>Once the state sare mapped to the events, the widgets add events to the BloC, which in turn yields states to the widgets subscribed to the BloC stream and rebuilds them with the new state.</p><p><strong>flutter_bloc </strong>uses <strong>InheritedWidget </strong>only to provide the BloC, while <strong>provider </strong>uses it for notification and providing.</p><p><strong>states_rebuiler </strong>is yet another state management technique. It uses the observer pattern for notification and the service locator pattern to provide the state; this is done in a rather particular way.</p><p>Notification with <strong>states_rebuilder </strong>is special because it can be done <strong><em>implicitly and can be filtered</em></strong>, that is, there is no need to explicitly use a package-specific or flutter-specific method to notify widgets. Your logic, your models, the BloCs — name them as you wish — are Vanilla Dart classes regardless of their complexity.</p><p>In turn, providing a state with <strong>states_rebuilder </strong>is very specific. Although it uses the s<strong>ervice locator</strong> pattern, it takes into account the life cycle of the widgets. This means that the models are added to the global container in the <strong>initState()</strong> method of the <strong>Injector </strong>widget (a StatefullWidget type) and removed in the <strong>dispose()</strong> method. This is very useful if you want to clean the models after they are destroyed. Using the service locator makes the process of getting an injected model independent of the <strong>BuildContext </strong>availability. This facilitates the management of the dependency injection in the application.</p><p><strong>What is the added value of states_rebuilder?</strong></p><p>states_rebuilder differs from other state management solutions by the following facts:</p><p>1. Business logic (bloc) is made 100% of simple dart classes.<br>2. Bloc’s methods can return any type (void, primitive, object, future or stream). <br>3. Refactor any method to return any type without affecting the user interface code.<br>4. Use immutable or mutable objects or mix them.<br>5. Refactor from mutability to immutability (or from immutability to mutability) without changing a single line in the UI code.<br>6. Easily mange side effects (onSetState, onData, onError and onRenuildState).<br>7. Inject dependencies asynchronously. (Even flavors can be injected asynchronously).</p><h3>A line of code is worth a thousand words</h3><p>In what follows, I will explain the concepts of <strong>states_rebuilder </strong>by building an application that will handle complex and tricky state management requirements. The views will be very basic, so as not to overload them with code not related to state management.</p><blockquote>Although <strong>state_rebuilder </strong>models are pure Dart classes, you have complete control over when to send a notification and over which widgets the notification will be sent to.</blockquote><p>NB: I assume basic knowledge of Dart and Flutter, so I will only explain what relates to state management.</p><h4>Sénario one: Future counter with error:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dy3Wm9rQsjQUqB-oT4KJCg.png" /></figure><p>This is a pure Dart class, which increments a counter after a second of waiting and throws an error at random. The error is a class defined by the user.</p><blockquote>And what is a real application rather than dealing with synchronous and asynchronous methods and handling errors?</blockquote><p>As mentioned above, the first thing to do is to make a single instance of the model object accessible throughout the widget tree. In other words, we have to feed, provide or inject the model into the widget tree. And it’s the <strong>Inject </strong>term that’s chosen in the <strong>states_rebuilder </strong>library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kXWJAnVscFYCsMcYirQzzQ.png" /></figure><p>The role of the <strong>Injector </strong>widget is to create a single instance of each model defined with the <strong>inject </strong>parameter and expose it to its child widgets so that it can be accessed from any child widget.</p><p>To get an instance of an injected model, we use the static method ‘Injector.get’:</p><pre>final Foo foo = Injector.get&lt;Foo&gt;();</pre><pre>//starting from 2.0.0 update</pre><pre>final Foo foo = IN.get&lt;Foo&gt;();</pre><p>In the case where Dart can infer the type of the model, the generic type is optional.</p><pre>final Foo foo = Injector.get();</pre><p>Injected models are accessible even within the <strong>inject </strong>parameter. For example, if we want to inject two dependent classes, we can do it very simply like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*ap4hSEQcXnPDrxeD2i2Y1Q.png" /></figure><p>The order of the injection is not mandatory.</p><p><strong>Injector </strong>uses the type to get the injected instance. If you want to inject two instances of the same type, you can use the name parameter:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/964/1*ujJ0jRpD_KWRgyBWhJZlQg.png" /></figure><p><strong>Injector </strong>offers you a set of practical methods to help you manage the widget’s life cycle as well as the application:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sw-z7y3Uq3ip7oHl5917sQ.png" /></figure><p>NB: <strong>Inject </strong>has three other parameters that we will see in this article and the following ones</p><h4>Get with Reactivity:</h4><p>Getting (or consuming) the model injected with the <strong>Injector.get</strong> method returns the registered singleton of the model.</p><p>For the injected model to be reactive, that is, widgets can register as listeners in the model, and the model can notify registered widgets, you must get the singleton wrapped in a reactive environment. To do so, use <strong>Injector.getAsReactive </strong>method :</p><pre>final ReactiveModel&lt;Foo&gt; foo = Injector.getAsReactive&lt;Foo&gt;();</pre><pre>//starting from 2.0.0 update<br>final ReactiveModel&lt;Foo&gt; foo = RM.get&lt;Foo&gt;();</pre><p>Notice that the return type is <strong>ReactiveModel&lt;Foo&gt;</strong>. The following picture shows the difference between <strong>Injector.get </strong>and <strong>Injector.getAsReactive </strong>methods:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/405/1*euYYiiE-m8pUKk_cHj75Eg.png" /></figure><p>As you can see, <strong>Injector.get</strong> returns the raw registred singleton of the Foo class and the <strong>Injector.getAsReactive</strong> returns the same raw singleton decorated with a reactive environment. The reactive environment adds the following getters and methods:</p><p>The getters are :</p><p><strong>state:</strong> returns the raw singleton model.</p><p><strong>connectionState</strong> : It is of type <strong>ConnectionState </strong>(a Flutter defined enumeration). It takes three values:<br>1- <em>ConnectionState.none: </em>Before executing any method of the model. (Vergin model before calling any of its methods or mutating its state).<br>2- <em>ConnectionState.waiting:</em> While waiting for the end of an asynchronous task.<br>3- <em>ConnectionState.done:</em> After running a synchronous method or the end of a pending asynchronous task.</p><p><strong>hasError: </strong>It’s of the bool type. it is true if the asynchronous task ends with an error.</p><p><strong>error:</strong> Is of type dynamic. It holds the thrown error.</p><p><strong>hasData:</strong> It is of type bool. It is true if the <strong>connectionState </strong>is done without any error.</p><p><strong>customStateStatus:</strong> It is of type dynamic. It holds your custom-defined state status. For example, in a timer app, you can define custom states such as ‘plying’, ‘paused, ‘finished’. (This will be the subject of the third part of this article).</p><p><strong>subscription:</strong> it is of type <strong>StreamSubscription&lt;T&gt;</strong>. It is not null if you inject streams using <strong>Inject.stream</strong> constructor. It is used to control the injected stream. (This will be the subject of the third part of this article).</p><p>and one method:</p><p><strong>setState(T state):</strong> return a <strong>Future&lt;void&gt;</strong>. It takes the state as a parameter that corresponds to the singleton instance of the injected model. It is used to mutate the state and notify listeners after state mutation.</p><p>Let’s continue building the UI and see some of the reactive environment getters and method in action:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-TxyN6-LmJYCMA57xr4REg.png" /></figure><p>Notice that <strong>Injector.getAsReactive</strong> is invoked without any parameters. This is an important point and we will come back to it very soon.</p><p>The result of <strong>Injector.getAsReactive </strong>is a reactive singleton of the injected model.</p><blockquote><strong>states_rebuilder </strong>caches two singletons; the first is the raw singleton model (obtained by the <strong>Injector.get method</strong>) and and the second is the reactive singleton that wraps the raw singleton (obtained by <strong>Injector.getAsReactive method)</strong>.</blockquote><p>Any action or event that changes the state and notifies the listening widgets must be called inside the <strong>ReactiveModel.setState</strong> method. And that’s exactly what’s happening in the <strong>onPressed </strong>callback of <strong>FAB</strong>.</p><h4>The state management wheel:</h4><p>The following picture shows the cycle of state management</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/1*fv46zfbBHk5gMdzL42suHw.png" /></figure><p>First, the state is your singleton instance of the model. From the user interface, you trigger an event or action that changes the state using the <strong>setState </strong>method. After state mutation, the UI will be notified to rebuild itself to reproduce the new state.</p><pre>onPressed: (){<br> counterModel.setState(FutureCounterWithError state){<br>  <strong>return state.increment();</strong><br>  }<br> }</pre><p>Notice that I returned the result of <strong>state.increment()</strong> because states_rebuilder uses the return type to check for asynchronous methods. (the use of the arrow function is very convenient).</p><p>Often, we want to trigger side effects events after mutating the state.</p><blockquote>side effects are what is not related to the UI build. Such as printing something in the console, showing snackbar and dialogs, opening drawer, calling external api.</blockquote><p>That’s what we want in our demo application. We want to display an error dialog box that displays the thrown error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gw5eqlEtOd1coztuAQI-Lg.png" /></figure><p>First of all, we set the <strong>catchError </strong>property to true because we are certain that the method can end with an error and we want to silent it so as not to break the application.</p><p><strong>onSetState </strong>takes <strong>BuildContext </strong>as a parameter and uses it to display <strong>AlertDialog </strong>after checking if the model throws an error using the <strong>hasError </strong>getter. The getter <strong>error </strong>returns the error object and it is used to display the error message.</p><p>From <strong>onSetState</strong>, you can call another <strong>setState </strong>and change the state, then notify the user interface. And from the last <strong>setState</strong>, you can use another <strong>onSetState </strong>to run other side effects, and so on. theoretically, without limit.</p><p><strong>onSetState </strong>is called after the state is changed and notification is sent and just before rebuilding the widget. If you want to run the side effects after the rebuild process is complete, use the <strong>onRebuildState </strong>method.</p><blockquote>To trigger side effects after the state change and just before rebuilding the listening widgets, use <strong>onSetState</strong>.<br>To trigger side effects after the rebuild process is completed, use the <strong>onRebuildState </strong>method.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GgL_DD_l8lYdggo0b16SOQ.png" /><figcaption><strong>onSetState vs onRebuildState</strong></figcaption></figure><h4>Registering widgets in the model.</h4><blockquote><strong>states_rebuilder </strong>register widgets by two means:<br>1- <strong>Injector.getAsReactive(context : context);</strong> with context defined. (This feature is removed from update 2.0.0)<br>2- <strong>StateBuilder</strong> widget. (<strong>WhenRebuilder</strong>, <strong>WhenRebuilderOR</strong>, <strong>OnSetState </strong>are other wigets to register to a reactive model add from 2.0.0 update)</blockquote><p>Let’s continue with our code</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oU4mb2aCWWyPAsxCANuzlw.png" /></figure><p>The difference between <strong>Injector.getAsReactive()</strong> without context and <strong>Injector.getAsReactive(context: context)</strong> with context is that the latter subscribe the widget that has the context to the obtained model.</p><blockquote>With <strong>states_rebuilder</strong>, if you want to get the reactive singleton of the model without wanting to rebuild the widget use <strong>getAsReactive()</strong> without the context. Whereas if you want the widget to be notified by <strong>setState </strong>method use <strong>getAsReactive(context: context)</strong> with the context.</blockquote><blockquote><strong>NOTE: Subscription with context feature is deprecated and removed from update 2.0.0</strong></blockquote><p>The remainder of the code is very simple to understand:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VZRQEy0aa3_5a1Y0rOKvwA.png" /></figure><p>With a series of if statement blocks, we specify what to display in each case:</p><p>First, if <strong>connectionState </strong>is <strong>none</strong>, that is, before pressing FAB, we display a text to tell the user what to do.</p><p>Second, once the <strong>connectionState </strong>is waiting, we display a <strong>CircularPrgressIndicator</strong></p><p>Third, if the <strong>connectionState </strong>is not <strong>none </strong>and not <strong>waiting</strong>, then it is <strong>done </strong>and we can safely get the counter value and display it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*QdXHyBytVGIawVe2oVHYyg.gif" /></figure><p><strong>NB:</strong> It happens that in certain practical situations, we want to trigger a method with and sometimes without wanting to notify the tree of the widgets. <strong>states_rebuilder </strong>gives you this choice.</p><p>In our example, If you want to notify listeners, use</p><pre>counterModel.setState((state)=&gt;state.increment());</pre><p>and if you do not want to notify listeners after state mutation, use</p><pre>counterModel.state.increment();</pre><p>That’s it. the code of this example is available <a href="https://github.com/GIfatahTH/states-rebuilder-examples/tree/master/001-future_counter_with_error">here</a>. try it yourself.</p><p>You might say that the idea of ​​getting a raw model singleton and surrounding it with what’s called a reactive environment is very simple and works for simple models only and not for models with many independent asynchronous methods. Indeed, the environment of the reactive model is shared between all the methods of the model, if one of them throws, all listeners will be notified with the error, which will pollute the reactive environment for the other methods.</p><p>Let’s imitate this scenario with the following example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RegdEZdMAssKVTGMkT0Hkg.png" /></figure><p>The <strong>increment </strong>method takes an integer parameter to customize the time of waiting. Also, the error depends on the ‘<strong>seconds’ </strong>parameter.</p><p>I will use two FABs: <br>1- The blue one that will control the blue counter and display the blue <strong>CircularProgressIndicator </strong>for <strong>one </strong>second. <br>1- The green one that will control the green counter and display the green <strong>CircularProgressIndicator</strong> for <strong>two </strong>seconds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AEKhX6AJZSuuMiEZ37Q3Ew.png" /></figure><p>The shared code for displaying <strong>AlertDialog </strong>is extracted in a local <strong>_showAlertDialog </strong>method.</p><p>The body of the <strong>scaffold </strong>that displays the green and blue counter is the following</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*woKvisgLORPheMKcFSczuQ.png" /></figure><p>Again, shared code is extracted to a local method to avoid repeating ourselves.</p><p>Whenever one of the FAB is tapped, both the blue and green counters are notified. You might say that this is very normal because both FABs when tapped, trigger the same method <strong>increment()</strong>. Can this be solved?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*ebs4ILvfVGJ4BT7QxU8TOg.gif" /></figure><p>Yes!, and even with the same method, with <strong>states_rebuilder</strong>, you can have precise control over which part of the widget tree will be rebuilt after the <strong>setState </strong>call.</p><blockquote><strong>States_rebuilder </strong>gives you fine-tuned control over the widget tree. With the <strong>setState </strong>method, you can call the same method multiple times, but notifying each time different widgets of your choice.</blockquote><p>For this purpose, <strong>states_rebuilder </strong>offers you the <strong>StateBuilder </strong>widget.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ps94RKCoWeYeaQ5reKFvQg.png" /></figure><p>You wrap any part of the widget you want to control by the StateBuilder widget.</p><p><strong>StateBuilder </strong>takes a list of models. Whenever one of the defined models sends a notification, the <strong>builder </strong>callback is called and what it contains will be rebuilt. The <strong>tag </strong>parameter is optional and, when set, it identifies this widget and the <strong>builder </strong>callback can be selectively called using this <strong>tag</strong>. In other words, reactive models can send a notification with a list of filter tags. Only widgets for which their tags are listed in the sent filter list will be rebuild.</p><blockquote><strong>tag </strong>is of dynamic type and can take any form of data. You can use enumeration instead of Strings to take advantage of your favorite IDE.</blockquote><p>In our example, in the <strong>onPressed </strong>callback and in the <strong>setState </strong>method, we use the <strong>filterTags </strong>parameter to define a list of tags to send with the notification.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HKXGCkEGHoLVT7EPhD0CSg.png" /></figure><p>The resultant GIF is :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*1W-wlXyIKIqUe3Jgrc10-Q.gif" /></figure><p>The code of this example is available <a href="https://github.com/GIfatahTH/states-rebuilder-examples/tree/master/002-double_future_counter_with_error">here</a>. try it yourself.</p><p>StatesBuilder offers many useful parameters that will discover in the next article:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BIbgqZSzqh5rPwxz5vTwRg.png" /></figure><p>This marks the end of this warm-up party. You have seen the main concepts of <strong>states_rebuider</strong>. In the next article, you’ll discover other important features that make it easy for you to manage complex and tricky state management situations.</p><ul><li>Part two of the article is <a href="https://medium.com/flutter-community/state-management-gymnastics-using-states-rebuilder-part-2-a7fa0dd7dc51">here</a>.</li></ul><ul><li><a href="https://pub.dev/packages/states_rebuilder">states_rebuilder | Flutter Package</a></li><li><a href="https://www.twitter.com/FlutterComm">JavaScript is not available.</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ba3a6abf9c7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/flutter-community/state-management-gymnastics-using-states-rebuilder-part-1-3ba3a6abf9c7">State Management Gymnastics using states_rebuilder. Part 1.</a> was originally published in <a href="https://medium.com/flutter-community">Flutter Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An Easy and Effective State  Management Solution for Flutter to achieve 100 % separation of…]]></title>
            <link>https://medium.com/flutter-community/an-easy-and-effective-state-management-solution-for-flutter-to-achieve-100-separation-of-f3d6988c2cac?source=rss-818757b53c98------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3d6988c2cac</guid>
            <category><![CDATA[development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[dart]]></category>
            <dc:creator><![CDATA[MELLATI Fatah]]></dc:creator>
            <pubDate>Mon, 21 Oct 2019 10:01:01 GMT</pubDate>
            <atom:updated>2019-12-06T15:13:24.105Z</atom:updated>
            <content:encoded><![CDATA[<h3>An Easy and Effective State Management Solution for Flutter to achieve 100 % separation of concerns</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*vBHeAeSEccSwWGS14L0W-g.png" /></figure><p>Every programmer wishes to achieve a complete separation between the hidden business logic and the visual user interface (UI). Complete separation means that the logic classes don’t know and don’t care about which UI framework is using them. Even for notification, logic classes don’t notify UI views about any change in their state. It’s the responsibility of the UI views to track any change in the logic state and update themselves. How to manage the state in this kind of situation? knowing that business classes can have <strong><em>Futures </em></strong>and UI classes need to be notified when <strong><em>Futures </em></strong>complete?</p><p>This article addresses this question by introducing the new version of the <strong><em>States_rebuilder</em></strong> package in which the responsibility of notifying changes is moved from the model classes to the user interface views, thus, leaving the logical classes simple, modular, testable, maintainable and portable.</p><h3>Counter App:</h3><p>To see how things work differently with <strong>states_rebuilder</strong>, let’s start with the simplest app in the world; The Counter App.</p><p>This is the model class:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/227/1*OnHYotqL4UWHQR_LomUn4w.png" /></figure><p>There is no simpler than this; No inheritance, no notification (as in <strong><em>provider </em></strong>and similar packages), no streams (as in <strong><em>bloc </em></strong>pattern), no annotation and code generation (as in <strong><em>mobX</em></strong>). The model is a simple dart class that is totally separated from the UI framework (Flutter in our case). No matter how big and complex the class model is, in the <strong><em>states_rebuilder </em></strong>solution, it is only a simple dart class.</p><p>How will be the UI part? Will it be as simple as the model is? How it can be notified when the counter value changes? Let’s see.</p><p>Here is the UI. See if you can understand it! I will explain it!</p><p>After important states_rebuilder dependency:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*QcLWcaqYU2lj4kLbmW1S0A.png" /><figcaption>getAsModel is deprecated, use getAsReactive instead</figcaption></figure><p>The UI consists of simple flutter widgets. It is only the lines indicated by arrows that make the difference and make what looks like stateless widgets to be reactive.</p><p>(1) — <strong>Meet the Injector widget:</strong> The <strong><em>Injector </em></strong>is a widget that makes models available to its child widgets that need it. The <strong><em>inject </em></strong>parameter of the <strong><em>Injector </em></strong>takes a list of <strong><em>Inject </em></strong>classes. The <strong><em>Inject </em></strong>constructor takes what is called the creation function which is of the type T function() . You can inject (or provide) many models at the same time; for example:</p><pre>Injector(<br> inject: [<br>  Inject&lt;Counter&gt;(() =&gt; Counter()),<br>  Inject&lt;HomeService&gt;(()=&gt;HomeService()),<br>  Inject&lt;LoginService&gt;(()=&gt;LoginService),<br> ],</pre><pre>builder: (_, __) { ........<br>.....<br>.....</pre><p>Child widgets that need to access one of the injected (provided) model uses the static method <strong><em>Injector.getAsReactive&lt;T&gt;()</em>.</strong></p><p>If you have noticed in the UI code above, <strong><em>Injector.getAsReactive </em></strong>is called without the <strong><em>context </em></strong>(line 15) and with the <strong><em>context </em></strong>in (line 32). context in <strong><em>states_rebuilder</em></strong> is optional. You use <strong><em>context </em></strong>with widgets you want to rebuild when the state of the model changed. On line 15, we get the model without context because we didn’t want the <strong><em>App </em></strong>widget to rebuild when the state of the model changes. In contrast, we want the <strong><em>MyHome </em></strong>widget to rebuild after incrementing the count and for this reason, the context is provided on line 32.</p><blockquote>If you want any child widget to listen to changes of a provided model, get the model with the context parameter.<br><strong>Injector.<em>getAsReactive</em>&lt;Counter&gt;(context:context);</strong></blockquote><blockquote>if you want only to get the model without listening to changes, get it without the context parameter<br><strong>Injector.<em>getAsReactive</em>&lt;Counter&gt;();</strong></blockquote><p>(2) — To notify subscribed widgets after any change in the state of a particular injected model use <strong><em>setState </em></strong>method:</p><pre>onPressed: () =&gt; counter.setState((Counter state) =&gt; state.increment())</pre><p>(3) — To get the state of any injected model, use the getter <strong><em>state</em></strong>:</p><pre>Text(&quot;${counter.state.count}&quot;),</pre><p>This how a reactive counter app looks like. And there is even more!</p><h3>Future counter app:</h3><p>It is very common to deal with <strong><em>Futures </em></strong>in your app, such as when fetching data from another service or database. In these cases, we want our app to rebuild when the future completes reproducing the newly received state.</p><p>This is an example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/417/1*PTDr0LY61aDAGCUakbQM_g.png" /></figure><p>I changed the <strong><em>increment </em></strong>method to be asynchronous and wait for one second before incrementing the <strong><em>count</em></strong>. Again, nothing special; it is a simple dart class.</p><p>For the UI part, you change nothing and believe it or not it will work. After tapping on the FAB button, the counter changes after one second.</p><p>To complicate the situation a little bit, I want to show a circular progress bar while waiting for the future.</p><p>This is the model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/435/1*XoZrDqz_l5souO7OUShyBg.png" /></figure><p>Here is the UI part. Changes from the simple counter app are highlighted:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/489/1*2YlTelFRNHrGHbVHvnJrMA.png" /><figcaption>getAsModel is deprecated, use getAsReactive instead</figcaption></figure><p>In the <strong><em>onPressed </em></strong>method, I used the <a href="https://www.tutorialspoint.com/programming_example/CDjWMF/dart-programming-cascade-operator">cascade operator</a> to: first, set the <strong><em>isActive </em></strong>to false and then call the <strong><em>increment </em></strong>method.</p><p>This is the GIF of the app:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*WE8QcIeffqTER1c9yLzKXg.gif" /></figure><p><strong><em>Update:</em></strong></p><p>After posting the article, I noticed that I added the <strong><em>isActive </em></strong>boolean variable to help in the conditional display of <strong><em>CircularPrograssIndicator</em></strong>. This can be considered to be a violation of the separation of concerns’ principle because the utility of the <strong><em>isActive </em></strong>variable is in the UI rather than in the model. So let’s remove the <strong><em>isActive </em></strong>variable from the model, and let’s see how to track the future, and show the <strong><em>CircularPrograssIndicator </em></strong>accordingly:<br>The model returns back to its simplest form:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/417/1*PTDr0LY61aDAGCUakbQM_g.png" /></figure><blockquote>The model is written for the business logic, not to serve the UI!.</blockquote><p>The UI becomes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*Dky8xkj5LBC67x4F5RtCag.png" /><figcaption>getAsModel is deprecated, use getAsReactive instead</figcaption></figure><p>I removed the cascade operator and use <strong><em>setSate </em></strong>for incrementing the counter as in the first example of the simple counter.</p><p>The second part is what does the job. The counter has a snapshot of type <strong><em>AsyncSnapshot&lt;counter&gt;.</em></strong> It holds the connection state :(<strong><em>waiting: </em></strong>for future; <strong><em>done: </em></strong>after future completes and, <strong><em>active: </em></strong>before first calling the future); similar to what we found in <strong><em>StreamBuilder </em></strong>widget. I took advantage of this property and display the <strong><em>CircularPrograssIndicator </em></strong>while waiting for the <strong><em>Future </em></strong>to complete. Yet another level of separation of concerns!</p><h3>Stream and future injection:</h3><p>With <strong><em>states_rebuilder </em></strong>you can inject <strong><em>stream&lt;T&gt;</em></strong> and/or <strong><em>future&lt;T&gt;</em></strong> and exposes a <strong><em>snapshot&lt;T&gt;</em></strong> to the child widget tree.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/1*DJMl8ZFJ2_vX-orHJqFdxA.png" /><figcaption>getAsModel is deprecated, use getAsReactive instead</figcaption></figure><p>(1) — Named constructor is used to inject <strong><em>streams </em></strong>and <strong><em>futures</em></strong>. In the future case, an initial value is defined.</p><p>(2) — To get the emitted value we use <br><strong><em>* Injector.getAsReactive&lt;int&gt;().snapshot</em> </strong>for the stream because the stream emits an int value<strong>.<br><em>* Injector.getAsReactive&lt;bool&gt;().snapshot</em> </strong>for future because the future completes with a bool value.</p><p>(3) — The emitted value is of type <strong><em>AsyncSnapshot&lt;T&gt; </em></strong>from which you can get data or error and check if it has data or error</p><p>It is important to know that streams are automatically unsubscribed when the <strong><em>Injector </em></strong>widget is removed from the widget tree.</p><p>The resultant GIF is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*1d7nClCZ1JqqptiZItSOcw.gif" /></figure><h4>Remarks:</h4><p>1- To make the distinction between two provided values with the same type, you can use the name parameter in the <strong><em>Inject </em></strong>constructor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/489/1*ZhtIasldKtCSAh7FAsyrNQ.png" /></figure><p>to get the injected value with a name, you use:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*3tYBjJYtOk89Baf-zLTJTA.png" /></figure><p>You can use the enumeration to name injected values:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*g59eADCbMTsNGgtw0Mq0oA.png" /></figure><p>2- To get the injected model, we used <strong><em>Injector.getAsReactive&lt;T&gt;(). </em></strong>The return type of <strong><em>Injector.getAsReactive&lt;T&gt;() </em></strong>is<strong><em> ModelStatesRebuilder&lt;T&gt;. </em></strong>This is useful when we want to make the model reactive. Reactive here means that we can register widgets using the <strong><em>context </em></strong>and get model state and mutate it using the <strong><em>state </em></strong>getter and <strong><em>stateState </em></strong>method as shown in the examples above.</p><p>In case we want to get the model without reactivity, we can simply use <strong><em>Injector.get&lt;T&gt;(). </em></strong>The return type of<strong><em> Injector.get&lt;T&gt;() </em></strong>is<strong><em> T.</em></strong></p><p>3- Injected models are injected lazily. This means that model classes are not instantiated and Future and Stream are not started until the first use. To instantiate an injected model at the time of registration, set the parameter<strong><em> isLazy </em></strong>of the Inject contractor to false.</p><h3>BloC pattern:</h3><p>If you like working with streams and <strong><em>rxDart </em></strong>library, you can use it with <strong><em>states_rebuilder </em></strong>to simplify the UI part of your app.</p><p>Here is an example of a login screen that has two text fields; one for the user email and the other for the user password, and one submit button. The submit button is disabled until the two text fields are validated. <br>NB: The example is inspired from this <a href="https://github.com/iampawan/FlutterLoginPageBloc">repo</a>.</p><p>Here is the model:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/099d18a5493ebd36e49546f34a3c66fe/href">https://medium.com/media/099d18a5493ebd36e49546f34a3c66fe/href</a></iframe><p><a href="https://gist.github.com/GIfatahTH/5a8097f5ffb626dcc4d30861681a0844">Here is the link of the code</a></p><p>If you are used to the BloC pattern, you see that there is nothing special in the <strong><em>LoginFromModel </em></strong>class.</p><p>The UI part is:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4724dc6908f5b2c77b9a2218fc812d60/href">https://medium.com/media/4724dc6908f5b2c77b9a2218fc812d60/href</a></iframe><p>Here <a href="https://gist.github.com/GIfatahTH/abcdcfb849e85c79ec1990c71add1f56">is the link to the code</a></p><p>(line 7)__ Injecting the <strong><em>LoginFromModel </em></strong>class<br>(line 9–10) — <br>* getting the injected instance of <strong><em>LoginFromModel </em></strong><em>using the </em><strong><em>get m</em></strong><em>ethod and not the</em><strong><em> getAsReactive. <br>* </em></strong>injecting the email stream with the custom the name of “emailStream”<br>(lines 13–14) — <br>* getting the injected instance of <strong><em>LoginFromModel </em></strong><em>using the </em><strong><em>get </em></strong>method and not the<strong> <em>getAsReactive. <br>* </em></strong>injecting the password stream with the custom the name of “<strong><em>passwordStream</em></strong>”<br>(line 17) — because we are using <strong><em>StreamControllers</em></strong>, we have to dispose them to release resources. For this purpose, we set the <strong><em>disposeModels </em></strong>parameter to true. The <strong><em>dispose </em></strong>method of the injected model (if they have one) will be called when the <strong><em>Injector </em></strong>widget is removed from the widget tree.<br>(line 19 — ) getting the injected instance of <strong><em>LoginFromModel </em></strong><em>using the </em><strong><em>get </em></strong>method because we do not want the <strong><em>LoginFromModel</em></strong> to be reactive.<br>(lines 20 -24) — getting the snapshot of the streams using <strong><em>getAsReactive </em></strong>with the context to register it so when the stream emits a value the widget will rebuild.<br>The remaining part of the code is easy to understand.</p><p>This is the GIF of the resulting APP:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*v7lkFSaEehc1x_I-IEVDAA.gif" /></figure><p>This is the end of this part. <strong><em>states_rebuiler </em></strong>offers more features that I will talk about in the next post.</p><p>To get the code, it’s <a href="https://github.com/GIfatahTH/states_rebuilder">here </a>in the example folder.</p><p><a href="https://pub.dev/packages/states_rebuilder">states_rebuilder | Flutter Package</a></p><p><strong>Thanks for your time.</strong></p><p>Hope you see the simplicity of the solution and like it, if yes <strong>clap and share</strong></p><p><a href="https://www.twitter.com/FlutterComm">JavaScript is not available.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3d6988c2cac" width="1" height="1" alt=""><hr><p><a href="https://medium.com/flutter-community/an-easy-and-effective-state-management-solution-for-flutter-to-achieve-100-separation-of-f3d6988c2cac">An Easy and Effective State  Management Solution for Flutter to achieve 100 % separation of…</a> was originally published in <a href="https://medium.com/flutter-community">Flutter Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[states_rebuilder and animator articles]]></title>
            <link>https://medium.com/@meltft/states-rebuilder-and-animator-articles-4b178a09cdfa?source=rss-818757b53c98------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b178a09cdfa</guid>
            <dc:creator><![CDATA[MELLATI Fatah]]></dc:creator>
            <pubDate>Fri, 18 Oct 2019 00:15:12 GMT</pubDate>
            <atom:updated>2020-06-18T22:43:31.661Z</atom:updated>
            <content:encoded><![CDATA[<p>These are friends link:</p><h3>states_rebuilder</h3><ul><li><a href="https://medium.com/flutter-community/immutable-state-management-rebuilder-how-to-refactor-to-immutability-and-vice-versa-b9576d6744f2">Immutable State Management Rebuilder. How to refactor to immutability and vice versa.</a></li><li><a href="https://medium.com/@meltft/3ba3a6abf9c7?source=friends_link&amp;sk=f963199ead3df973f07f56be005bf46b">State Management Gymnastics using states_rebuilder. Part 1.</a></li><li><a href="https://medium.com/flutter-community/state-management-gymnastics-using-states-rebuilder-part-2-a7fa0dd7dc51">State Management Gymnastics using states_rebuilder. Part 2.</a></li><li><a href="https://medium.com/flutter-community/clean-architecture-with-states-rebuilder-has-never-been-cleaner-6c9b91c3b9b6">Clean Architecture with states_rebuilder has Never Been Cleaner</a></li><li><a href="https://medium.com/flutter-community/an-easy-and-effective-state-management-solution-for-flutter-to-achieve-100-separation-of-f3d6988c2cac?source=friends_link&amp;sk=56997a53b12b9faf0395145a30acc4ca">An Easy and Effective State Management Solution for Flutter to achieve 100 % separation of concerns</a></li><li><a href="https://medium.com/flutter-community/widget-perfect-state-management-in-flutte-is-it-possible-73e76c205620?source=friends_link&amp;sk=2a8fdcb330e8f83e51e36429fc3f2508">Widget-Perfect State Management in Flutter! Is it Possible?</a></li><li>ResoCoder YouTube video</li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FiIxWMeFnIKA%3Ffeature%3Doembed&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DiIxWMeFnIKA&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FiIxWMeFnIKA%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/b65e5e602b1231fa6507c332e16c335c/href">https://medium.com/media/b65e5e602b1231fa6507c332e16c335c/href</a></iframe><h4>Earlier version</h4><ul><li><a href="https://medium.com/flutter-community/flutter-oneyearchallenge-scoped-model-vs-bloc-pattern-vs-states-rebuilder-23ba11813a4f?source=friends_link&amp;sk=3f2b9fefa32c5e591dadcdc95780b999">Flutter #OneYearChallenge; Scoped Model vs BloC Pattern vs States Rebuilder</a></li></ul><h3>animator</h3><ul><li><a href="https://medium.com/flutter-community/flutter-animation-has-never-been-easier-part-1-e378e82b2508">Flutter Animation has Never Been Easier — Part 1</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b178a09cdfa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Widget-Perfect State Management in Flutte! Is it Possible?]]></title>
            <link>https://medium.com/flutter-community/widget-perfect-state-management-in-flutte-is-it-possible-73e76c205620?source=rss-818757b53c98------2</link>
            <guid isPermaLink="false">https://medium.com/p/73e76c205620</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[MELLATI Fatah]]></dc:creator>
            <pubDate>Sat, 25 May 2019 10:01:00 GMT</pubDate>
            <atom:updated>2019-05-26T17:45:27.006Z</atom:updated>
            <content:encoded><![CDATA[<h3>Widget-Perfect State Management in Flutter! Is it Possible?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*zSQnnss0Sdx-D1wx_S-a2A.png" /></figure><p>If it happened that you read an introductory section about Flutter, you might have faced statements like “Flutter is a toolkit offered by Google to build cross-platform mobile, desktop and web applications from one source codebase”. Most likely, you have not missed the statement either that it is all widgets. It probably hit you too, that Flutter owns every pixel on the screen which allows it to be “Pixel Perfect”.</p><p>That is all nice and good but when it comes to state management in Flutter opinions diverge. Can any of the available state management techniques be qualified as the most optimal? I say optimal in the sense of easiness of implementation without losing the ability to surgically rebuild the widget tree whenever you want. Let’s find out together!</p><p>In the Google I/O 2019 event, the Flutter team took a choice and went with the Provider package as the recommended approach for state management. The good thing about this announcement is that Provider is a community-driven package. This reflects how open the Flutter team towards community contributions is. This announcement is not only a recognition to the creator of the Provide alone, yet also a message to all the community members to encourage them to try to found their solutions. In this article, I will present one contributional effort to make state management in Flutter as easy and as effective as possible.</p><h4>states_rebuilder:</h4><p>The states_rebuilder package is based on the principle of separation of concerns. It is a design principle for separating your application into distinct sections so that each section addresses a separate concern. In this case, you define a logic class to hold all of your application logic and provide this class to your User Interface (UI) to make it accessible from all your widgets.</p><h4>Providing BloCs:</h4><p>The first Widget offered by states_rebuilder package is BlocProvider whose sole role is to make an instance of MainBloc, for our example, available to the RoutPage and all its child widgets so that they can share data using the InheritedWidget behind the scene.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/377/1*op3hE6YEbMw8pvhiys1qdQ.png" /></figure><h4>Prepare the scene:</h4><p>The UI consists of a simple grid of 12 items. In the BloC, there is a counter variable and an increment() method to increment the counter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*oMzU7TsHNjrj7X2y_gAb9A.png" /><figcaption>The UI part before reactivity</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*JJwU9c5PRPoWwebYdfjXPw.png" /><figcaption>The logic of the app</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/406/1*9otUja6gflMa--IwLIlOXQ.png" /><figcaption>Simple 3 x 4 grid displaying the value of the counter</figcaption></figure><p>Our app is stateless and it is not reactive. Let’s use the strength of states_rebuilder to add reactivity.</p><h4>Rebuild all:</h4><p>The second widget offered by the states_rebuilder package is the StateBuilder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*zfFMy0hNc1RJwKjxWSRSdg.png" /><figcaption>Wrap what you want to make reactive with StateBuilder and define the two required parameters</figcaption></figure><p>Wrap what you want to make reactive with StateBuilder and define at least two required parameters:</p><p>1- blocs: a list of instances of your logic classes you want the StateBuilderto subscribe to the list of listeners;<br>2- builder: a closure with two parameters, the first is of BuildContext type that holds the context of this widget, and the second of String type and it holds the identity (or the key or the address) of this widget. As we do not need them now,we just used underscores.We will use them late on in this article.</p><p>In the Bloc we use rebuildStates() to notify listeners subscribed in this particular BLoC to rebuild.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/446/1*eR4b1EVzJwit9SUzSOM_fw.png" /></figure><p>That all, when you tap on any of the boxes all of them rebuild.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/212/1*hkKyKHxeGG9tlJAE9bbIAw.gif" /><figcaption>rebuildState() without parameter rebuilds all the subscribed listeners</figcaption></figure><p>If you’re familiar with other libraries such as scoped_model and provider, we probably noticed that they achieve a similar behavior using notifyListeners. What makes states_rebuilder different is the fact that it gives you more capabilities to surgically rebuild the widget tree. Continue reading this article and I think you’ll be pleasantly surprised.</p><h4>Rebuild one:</h4><p>If you want to be widget perfect, you want to rebuild only the tapped box. This easily achieved with states_rebuilder:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*mPw-1u-P-g8QMYT4ZVi99A.png" /><figcaption>Rebuild the tapped box. Changes are highlighted</figcaption></figure><p>All the change you have to do on the UI are highlighted. Not much!<br>The second parameter of the builder closure is of type String. It stores the unique identity of the state (the address of the state). I choose to name it tagID, but it can be named tagMe, thisTag or any other name you think it is more descriptive. Just like the first parameter of the builder closure which you can name it context, or simple “c” or just an underscore if not used.<br>the logic class becomes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/1*taR9EAhuGBqh9k5tY8duSg.png" /><figcaption>When rebuildStates is called with a list of tags. StateBuilder with those tags will rebuild</figcaption></figure><p>This is how the app looks like after these tiny changes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/202/1*V4B2cLF8z9Jiii6LH8ECYA.gif" /><figcaption>Rebuild the tapped box. the second parameter of the builder closure is a String that holds the address of the tapped box.</figcaption></figure><p>Please note that all boxes hold the same value of the counter, but only the tapped one is rebuilt to reflect the updated value.</p><p>You see who easy it is, how efficient it is, how widget perfect it is!</p><h4>Rebuild a set:</h4><p>Let’s say you want to rebuild a set of boxes that have common criteria. In our example,let’s suppose that we want that all widgets that have an even index to rebuild all together. Also, we want the same thing to widgets that have an odd index.</p><p>The fact that we want to rebuild a specific set of boxes leads us to distinguish them form other boxes. This is achieved by giving them a name or tagging them so that when reBuildStates is called with the chosen tag, those widgets that have this tag will rebuild. The tag parameter in the states_rebuilder is dedicated to such a use.<br>This is how the UI looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/553/1*c983JuCCkmDNwqmsFqu8_w.png" /><figcaption>tag can be any type of date. It is used to filter the list of widgets to rebuild when calling statesRebuilder</figcaption></figure><p>the bloc part remains the same.</p><p>the parameter tag is dynamic so that it accepts any type of data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/240/1*3E6mf09oYYyuaecVv_rY1A.gif" /><figcaption>All widget with the same tag will be notified to rebuild when rebuidStates is called with this tag</figcaption></figure><h4>Rebuild remote widget:</h4><p>To show more functionality, let’s say we want to add a widget to show if the tapped widget has even or odd index.<br>This is one possible implementation:<br>The UI part:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/1*wJwvI5W821eyN_sQjNoz0g.png" /><figcaption>Adding an Icon to show if index of the tapped box is even or odd. a circular progress bar is shown if no box is tapped</figcaption></figure><p>The bloc part:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*M1EpQ1ESJAQXM4rJ6lqTKQ.png" /><figcaption>rebuildStates take al list of dynamic tags</figcaption></figure><p>The solution is to use a StateBuilderwith a tag. We can choose a simple String to name our tag, but for a big project, it is preferred to use an enums so that we can make full profit of our preferred IDE helping functionality such as auto-completion, peek and show definition and references. The conventional place to declare your enums is in the same file where your BloC classes are. For a bigger project, it is even more helpful if you declare your enums in one file and import it when needed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/240/1*w20m2UwldYEGIo3iRhHwxQ.gif" /><figcaption>You can build any widget by given it a specif tag</figcaption></figure><h4><strong>A full functional statefulWidget:</strong></h4><p>StateBuilderoffers many other parameters to mimic all the functionality of a StatefullWidget:</p><pre><strong>StateBuilder</strong>(<br> {Key <strong>key</strong>, <br> dynamic <strong>tag</strong>, <br> List&lt;StatesRebuilder&gt; <strong>blocs</strong>, <br> (BuildContext, String) → Widget <strong>builder</strong>, <br> (BuildContext, String) → void <strong>initState</strong>, <br> (BuildContext, String) → void <strong>dispose</strong>, <br> (BuildContext, String) → void <strong>didChangeDependencies</strong>, <br> (BuildContext, String, _StateBuilder) → void <strong>didUpdateWidget</strong><br>})</pre><h4>StateBuilder with mixins:</h4><p>Are we saying goodbye to StatefulWidget? NO, because the state class of a StatefulWidget can be mixin with other class to support animation, tabView and many other things.<br>states_rebuilder offers the StateWithMixinBuilderwidget to handle some of the most commonly used mixins.</p><pre><strong>StateWithMixinBuilder&lt;T&gt;</strong>(<br>{Key <strong>key</strong>, <br> dynamic <strong>tag</strong>, <br> List&lt;StatesRebuilder&gt; <strong>blocs</strong>, <br> (BuildContext, String) → Widget <strong>builder</strong>, <br> (BuildContext, String, T) → void <strong>initState</strong>, <br> (BuildContext, String, T) → void <strong>dispose</strong>, <br> (BuildContext, String, T) → void <strong>didChangeDependencies</strong>, <br> (BuildContext,String, _StateBuilder, T) → void <strong>didUpdateWidget</strong>, <br> (String, AppLifecycleState) → void <strong>didChangeAppLifecycleState</strong><br>  <strong>MixinWith mixinWith</strong><br>})</pre><p>Mixin supported until now are singleTickerProviderStateMixin, tickerProviderStateMixin, AutomaticKeepAliveClientMixin and WidgetsBindingObserver.</p><p><strong>Animation Example:</strong></p><p>I won’t go through the details on how to use animation in Flutter. The aim of the example is to show you a practical case of using StateWithMixinBuilder.</p><p>If you want more details on how to set your animation, this is a good article about animation written by <a href="https://medium.com/u/f2233690754a">Raouf Rahiche</a>. (<a href="https://medium.com/flutter-community/twitter-animated-fab-how-to-do-it-in-flutter-daebc69cac30">link</a>)</p><p>The UI is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*foa3pDtQdbMjNSxMDFQOBw.png" /><figcaption>StateWithMixinBuilder is used to add some of common mixins support</figcaption></figure><p>The bloc is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*qrLs9WJEH8y5eNhY7VnZjA.png" /><figcaption>A typical animation setup</figcaption></figure><p>From the initState() of the StateWithMixinBuilder we call the initAnimation from the bloc with TickerProvider type parameter. It is here where all the conventional animation setup occurs.<br>In the triggerAnimation() of the bloc we added rebuildStates() as a listener, which means that all the boxes will rotate when any of them is tapped.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/240/1*PF8pKvMbGbtqzMJSd7g4HA.gif" /><figcaption>With one animation controller we can animate as many widgets as we want</figcaption></figure><p>To rotate only one box, we follow the same steps mentioned above.</p><p>The change in UI part.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*g3tW98U5E-jRmEw_L3nWgw.png" /></figure><p>The change in the bloc part</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/1*GcwFdqVKchkz1Z_muauKaw.png" /></figure><p>the result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/240/1*H3syr6aWQjMHbrGHuaXSMg.gif" /><figcaption>Rotating the tapped box. without removing the previous listener.</figcaption></figure><p>The last tapped box will continue to animate because listeners are not removed. Here is the bloc with removing listeners:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/383/1*Xaug2JLAXxT81Ss9iqU9fA.png" /></figure><p>The result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/240/1*Mei_xj7AdnCRX5xZxEN8Lg.gif" /><figcaption>Animating the tapped box after removing the last listener</figcaption></figure><p>To animation the even and the odd indexed boxes, there is no special thing, as mentioned in the steps above:</p><p>The change in the UI are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*A4iFiX5mdBg2M7fUVKOPUQ.png" /></figure><p>The result is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/240/1*-x9Qd2dUIL5WwU-4JXoNRw.gif" /><figcaption>Animating even indexed boxes when an even box is tapped. The same for odd indexed boxes</figcaption></figure><p>Based on the states_rebuilder, I created a library dedicated to the animation called the animator.</p><p><a href="https://pub.dev/packages/animator">animator | Flutter Package</a></p><p>This is an article explaining some of its functionalities.</p><p><a href="https://medium.com/flutter-community/flutter-animation-has-never-been-easier-part-1-e378e82b2508">Flutter Animation has Never Been Easier — Part 1</a></p><p><strong>AppLifecycleState Example:</strong></p><p>This is an example using <strong>AppLifecycleState </strong>to track the state of the app (onPause(), onResume() in Android).</p><p>The UI part:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*rjyM7Xd7UaZTvx7Sb835Pg.png" /></figure><p>The Bloc part, we add lifecycleState method:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/1*QNO5J0mbKy9_0nN--M4_Mw.png" /></figure><p>The result is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/262/1*WfCzOdPndGexei06cEILGw.gif" /></figure><p><strong>Performance consideration:</strong></p><p>As states_rebuilder rely on the speed of fetching data form Maps where listeners are stored, performance questions may arise. <br>I try to compare the time taken to execute the rebuildState() function with that taken by a simple print statement.</p><p>I followed this approach:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*lyvTs-L2RyGqguH6OUUCOg.png" /><figcaption>measure the execution time of rebuildState() on microseconds and compare it with print() statement</figcaption></figure><p>This is the result in the debug mode:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/370/1*If2npx9KHHjLk-5Xm8bxwg.png" /><figcaption>rebuildStates() for 12 grids VS print() results</figcaption></figure><p>The states_rebuild average is 50 microseconds and the print statement 20 microseconds in the debug mode.</p><p>I increased the number of grids to 500, the results are</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/379/1*QnuQHHdCmo5hOYmA_n9Akg.png" /><figcaption>rebuildStates() for 500 grids VS print() results</figcaption></figure><p>This means that the average time taken to mark 250 widgets as to need to rebuild is 150 microseconds in debug mode. IT is important to note that states_rebuilder stores only listeners which are mounted. When a state is disposed, its listener is removed. In most common situation states_rebuilder stores about tenths of listeners.</p><p>I used the same technique with notifyListener() used in scoped_model and provider, I found:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/191/1*cssBmR9jNjyztQFGjIKCqQ.png" /><figcaption>average time taken to execute notifyListeners is 50 microseconds</figcaption></figure><p>This is one contribution from the community to manage the states in Flutter. I hope we like it.</p><h4>states_rebuilderr for the web:</h4><p>The good news is that states_rebuilder works in the web just as well as it does in the mobile. This GIF shows all the above example with the same code in web browser:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/286/1*Em3ShmcRLong6NxQDamg6Q.gif" /><figcaption>states_rebuilder in the wab.</figcaption></figure><p>The full code of this article is <a href="https://github.com/GIfatahTH/states_rebuilder/tree/master/example">here</a>.</p><p>The page of the states_rebuilder is here.</p><p><a href="https://pub.dev/packages/states_rebuilder">states_rebuilder | Flutter Package</a></p><p>Happy to hear your claps, to read your comments, to react to your critics, to see your stars in GitHub and above all happy to be part of the great Flutter community.</p><p><a href="https://twitter.com/FlutterComm">JavaScript is not available.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73e76c205620" width="1" height="1" alt=""><hr><p><a href="https://medium.com/flutter-community/widget-perfect-state-management-in-flutte-is-it-possible-73e76c205620">Widget-Perfect State Management in Flutte! Is it Possible?</a> was originally published in <a href="https://medium.com/flutter-community">Flutter Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Animation has Never Been Easier — Part 1]]></title>
            <link>https://medium.com/flutter-community/flutter-animation-has-never-been-easier-part-1-e378e82b2508?source=rss-818757b53c98------2</link>
            <guid isPermaLink="false">https://medium.com/p/e378e82b2508</guid>
            <category><![CDATA[animation]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[cross-platform]]></category>
            <dc:creator><![CDATA[MELLATI Fatah]]></dc:creator>
            <pubDate>Thu, 14 Mar 2019 13:16:03 GMT</pubDate>
            <atom:updated>2019-12-17T20:04:27.883Z</atom:updated>
            <content:encoded><![CDATA[<h3>Flutter Animation has Never Been Easier — Part 1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*NF2mti4ytTyjKKxfBAyJ4Q.png" /></figure><h3>Introduction</h3><p>Adding animations to your app is an important part in the app development lifetime. Animation is used to add visual effects to notify users that some part of the app’s state has changed. It gives your app a polished look that witnesses the quality of your app to the end users.</p><p>Flutter has a very good animation library. Many articles have been written to explain the different parts of the Flutter animation library. In this article, I propose a new package that makes animation in Flutter as easy as the simplest widget in Flutter.</p><h3>Animator</h3><p><a href="https://medium.com/flutter-community/flutter-oneyearchallenge-scoped-model-vs-bloc-pattern-vs-states-rebuilder-23ba11813a4f">In my last article</a>, I introduced the states_rebuilder library.</p><p><a href="https://pub.dartlang.org/packages/states_rebuilder">states_rebuilder | Flutter Package</a></p><p>It is so an easy and so an effective state management technique, that I changed the way I look to animation in Flutter. I gathered my ideas on animation and created a new package which I called ANIMATOR.</p><p><a href="https://pub.dartlang.org/packages/animator">animator | Flutter Package</a></p><h3>Flutter create with states_rebuilder and animator:</h3><p>The main challenge of Flutter Create is to build something interesting, inspiring, and beautiful with Flutter using 5KB dart code. states_rebuilder and animator helps you reduce the amount of dart code in your app, especially if your app has many statefullWidgets and animations.</p><p>Take this example Form flutter documentation <a href="https://github.com/flutter/website/blob/master/examples/animation/animate3/lib/main.dart">website/examples/animation/animate3/lib/main.dart</a>. It has 60 lines and 1.63 KB.</p><p>With animator it looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/529/1*AddtYIjm2IbHswqC5Za3uA.png" /></figure><p>It has 21 lines and 0.58 KB which corresponds to 64% reduction of code size. The more your app has statefullWidgets and animations the more you gain in code size.</p><p>Let’s see what animator offers and how it animates widgets.</p><p>In flutter animation can be classified:</p><ul><li>Implicit: such as AnimatedContaine, AnimatedPadding, AnimatedPositioned and AnimatedDefaultTextStyle.</li><li>Explicit: Where you define AnimationController, Animation and Tween classes, and you should explicitly start, stop and listen to animation status.</li></ul><p>Following the same fashion, the Animator package offers implicit-like and explicit-like animation</p><h3>Implicit-like animation</h3><p>In Animator animation is nothing than:</p><p>1- Two values where the animation value changes between them. This is defined by Tween class;</p><p>2- The duration the animation takes. This is defined by Duration class;</p><p>3- The path or curve to define how the animation varies between the begin value and the end value. This is defined by Curves class;</p><p>4- The ability to control how many times the animation repeats, cycle back and forth, and when to stop it. This is defined by the repeats and cycles parameter of the Animator class;</p><p>5- The product of an Animation is an animation value which you can use to update the UI in each frame of the animation.</p><p>The figure bellow, sketches the above points, where:</p><ul><li>INPUT = points 1,2 &amp;3;</li><li>CONTROL = point 4 ; and</li><li>OUTPUT = point 5.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*-saqomXGhIpQnUXaZ6Z8SQ.png" /></figure><p>If I were to resume animation with Animator in one word, I would say TWEENs. Yes, the only part that makes and shapes your animation is Tween. In the remainder of this article and the next ones, I will go through all the available Tweens in Flutter and show you what can do with them.</p><h3>I- One Tween Animation:</h3><h4>I.1- Tween&lt;double&gt;</h4><p><strong>a - Opacity animation:</strong></p><p>The simplest and the most used Tween is the Tween&lt;double&gt;. Animation Opacity is a good starting point to dive into Animator. The GIF bellow shows different opacity animations that we will reproduce in the next couple of paragraphs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*knGdYVnPfjyKnUraQfZUYg.gif" /><figcaption>GIF 1 : Different types of Opacity animation</figcaption></figure><p><strong>1- Opacity widget. Default animation:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/1*LrDI0aO6fhHRBjVY5D6bJQ.png" /><figcaption>Default Opacity Animation. You can’t see the animation in the GIF because duration is short and is consumed during the route transition animation</figcaption></figure><p>After importing Animator, in the builder parameter of the Animator widget, you define the Opacity widget with opacity= anim.value. That’s all to animation the Opacity with the default animation. Default animation is:</p><ul><li>tween = Tween&lt;double&gt;(begin:0 , end:1);</li><li>duration = Duration(miliseconds : 500); and</li><li>curve= Curves.linear</li></ul><p>The animation starts automatically when the widget is rendered, and lasts only for one forward path (from beginning to the end). When animation is completed, it stops and the AnimationController is disposed to free resources.</p><p>With repeat parameter, you can define the number of repeats you want your animation to do before stopping it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/341/1*93Sjk0C1NTqQ8UDStflw7Q.png" /><figcaption>repeat the animation 5 times</figcaption></figure><p>repeats : 5 , means that animation goes from beginning to end and restart from the beginning five times before stopping and disposing AnimationController.</p><p>To infinitely repeat the animation put 0 in the repeats parameter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/351/1*ofCQ3Sn7gxm7yX4Pes6R-Q.png" /><figcaption>Infinitely repeat animation</figcaption></figure><p>If you want your animation to go both paths, forward and backward, use cycles parameter.</p><p>cycles = 2 (or 2 x 1), means that the animation goes forward and backward one time and stop at the beginning.</p><p>cycles = 3 (or 2 x 1+1), means that the animation goes forward then backward then forward again and stop at the end.</p><p>cycles= 10 (or 2 x 5), means that the animation goes forward and backward five times and stop at the beginning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/342/1*Cnoj5WSu442WLN3sF2B55Q.png" /><figcaption>Cycle animation 10 times ( animation goes back and forth 5 times)</figcaption></figure><p>To infinitely cycle the animation put 0 in the cycles parameter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/342/1*CiXDYqPpkHIdFwycv8NGiw.png" /><figcaption>Infinitely cycle animation</figcaption></figure><p><strong>2- FadeTransiton widget. Default animation:</strong></p><p>Flutter has many ready to use widgets for animation. With Animator you can make profit of these widgets.</p><p>FadeTransition animates the opacity of a widget.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/345/1*6F7izBgD_dvBGgsH8UabBw.png" /><figcaption>Opacity animation with FadeTransition widget</figcaption></figure><p>It’s important to note that opacity argument of FadeTransition takes Animation type value not a double value as we are used to with Opacity widget.</p><p>We can use repeats and cycles parameter of Animator to control the number of repeats and cycles the animation should take before stopping.</p><p>The first and second rows of the opacity GIF above show the same behavior although the first use Opacity and the second uses FadeTransition.</p><p>Animating opacity with Opacity widget and with FastTransition result in the same visual effect, but for performance considerations, the use of FaseTransition is preferred.</p><p>To avoid that animated widget (and possibly its subtree) from rebuilding each frame, you can store the widget in a final variable outside the Animator widget and use that variable in the builder argument of the Animator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/347/1*Vt9UANq7qaSO0El8qZMGSA.png" /><figcaption>To avoid widget rebuild each frame, declare it outside the Animator widget</figcaption></figure><p>3- <strong>FadeTransiton widget. Changing duration:</strong></p><p>The default duration is 500ms. You can customize this parameter to the duration you want your animation to take.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/341/1*6SMy31QRdfBSAVkq4yiQKg.png" /><figcaption>Animating opacity with FadeTransition. Changing duration to 2s</figcaption></figure><p>4- <strong>FadeTransiton widget. Changing Curve:</strong></p><p>You can change the default Curve with the help of the curve parameter of the Animator widget.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/349/1*oLsUW4kgidHM7V0yGshbyg.png" /><figcaption>Animating opacity with FadeTransition. Changing curve to Curves.elasticOut</figcaption></figure><p><strong>b- Rotation animation:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*6qvaFvWo3MHM_GxWFkEbmw.gif" /><figcaption>GIF 12 : Different types of Rotation animation</figcaption></figure><p><strong>1- Rotation around the center:</strong></p><p>With Tween&lt;double&gt;, we can easily rotate widgets with Animator. You have three widgets to animate rotation:</p><p>1- Transform.rotate widget;<br>2- Transform widget,<br>3- RotationTransition widget.</p><p>The first widget is Transform.rotate which takes a double value for the angle argument. the Tween with 0 and ends with 2*pi to complete one turn. The default origin of rotation is the center.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/345/1*bRzNxOrH3xX77DvLP67juA.png" /><figcaption>Rotation animation using the Transform.rotate widget</figcaption></figure><p>The second widget is the Transform widget which takes a Matrix4.rotationZ(anim.value) in the transform argument. You have to explicitly specify the alignment argument to be Alignment.center to center the origin of rotation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/342/1*R_jH23YYTBZbCCQiVNkRWw.png" /><figcaption>Rotation animation using the Transform widget</figcaption></figure><p>The third widget is the RotationTransition widget. It takes an Animation&lt;double&gt; type value for the turn argument to indicate the number of turns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*JNXF1tRM23IaoKyoKmmmsw.png" /><figcaption>Rotation animation using the RotationTransition widget</figcaption></figure><p>The three above widget reproduce the same animation effect.</p><p><strong>2- Rotation around X, Y and Z axis using the Transform Widget</strong></p><p>Transform widget is most suitable when you want to change the axis of rotation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*7gMwbOA2kihMwbmgBAj_6w.png" /><figcaption>Rotation animation. Changing the axis of rotation</figcaption></figure><p><strong>3- Changing the origin of rotation using the Transform.rotate widget</strong></p><p>In most cases where you want to rotate around the Z axis of the widget, use Transform.rotate. You have the ability to change the origin of rotation with the help of alignment and origin arguments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/1*R7Zv5QWpZ4vK-FYrnI-uIw.png" /><figcaption>Rotation Animation changing the origin of rotation using the alignment argument</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/351/1*GEYgCJUSjsUlAH9tRjslhQ.png" /><figcaption>Rotation Animation changing the origin of rotation using the origin argument</figcaption></figure><p><strong>4- Rotation animation with Transform.rotate. Changing curves</strong></p><p>The forth row in the GIF gives you a feeling of Curves.elasticOut, Curves.elasticIn, Curves.elasticInOut and Curves.bounceOut.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/1*7r12lMXTmke9gSRNjh1C2g.png" /><figcaption>Rotation animation. Changing the Curves</figcaption></figure><p><strong>c- Scale, SizeTransition and skew animation:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*qApo9fuM1CaE6Z2PBK72MQ.gif" /><figcaption>GIF 3: Different types of Scale, SizeTransition and skew animation</figcaption></figure><p><strong>1- Scale from center:</strong></p><p>Scale animation is achieved by:</p><ul><li>Directly by animating the width and height of SizedBox widget; the default Tween&lt;double&gt;(begin:0, end:1) is used</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/358/1*LUB7ZZIXJuo2WHjKy1X0vQ.png" /><figcaption>Scale animation using SizedBox</figcaption></figure><ul><li>Transform.scale widget;</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/1*S9UoQWltc9wTfVbtUN0QbA.png" /><figcaption>Scale animation using Transform.scale</figcaption></figure><ul><li>Transform widget. transform argument of Transform widget takes Matrix4.diagonal3Values(x,y,z). We are animation the x and y not the z component.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/354/1*tb9UZ6W-U7TCQXaOc_BPBA.png" /><figcaption>Scale animation using Transform</figcaption></figure><ul><li>ScaleTranstion widget.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*e6LdnL-6rRPn6beS1XvDeA.png" /><figcaption>Scale animation using ScaleTransition</figcaption></figure><p>For most practical cases animating the scale with Transform.scale is the best choice.</p><p><strong>2- Changing the origin of scaling using the Transform.scale widget:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/345/1*5_IVfsMC57FqcYmD_ShiGQ.png" /><figcaption>Scale animation. Changing the origin of scaling with the help of alignment argument</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/348/1*kLJo_-6AB3YAK54LRNIeAg.png" /><figcaption>Scale animation. Changing the origin of scaling with the help of origin argument</figcaption></figure><p><strong>3- Scale animation using Transform.scale widget. Changing curves:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/355/1*aAqvj8l9IzXtY8DgTAfS-g.png" /><figcaption>Scale animation. Changing curves</figcaption></figure><p><strong>4- SizeTransition animation</strong></p><p>SizeTransition animates its own width (or height) to clip its child horizontally (or vertically).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/359/1*GqQXLFDf-82wpFTMGRJx-g.png" /><figcaption>SizeTransition. the default axis of transition is vertical</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/1*8V3J6HVi6FX-mE7jhbnLJg.png" /><figcaption>SizeTransition. changing the axis of transition direction</figcaption></figure><p>We can change the axis of transition (the axis that sizeFactor is modifying it).</p><p>axisAlignment argument takes a double value. A value of -1 shifts the axis of transition to start when axis argument is Axis.horizontal (-1 indicates the top when axis is Axis.vertical).</p><p>The start is (the left when TextDirection.ltr, and on the right when TextDirection.rtl)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/347/1*-GtBFlfTKVNhcSknZTbXnA.png" /><figcaption>SizeTransition. Shifting the axis of transition to the start (the left when TextDirection.ltr, and on the right when TextDirection.rtl)</figcaption></figure><p>A value of 1 shifts the axis of transition to end when axis argument is Axis.horizontal (1 indicates the bottom when axis is Axis.vertical).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/351/1*636RdfPyPudOIXSSa_Jf4A.png" /><figcaption>SizeTransition. Shifting the axis of transition to the end(the right when TextDirection.ltr, and on the left when TextDirection.rtl)</figcaption></figure><p><strong>5- Skew animation:</strong></p><p>A Skew animation allows you to tilt the child in one direction while keeping the sides parallel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*UvbYBts_HWcpnB-OAKSzIA.png" /><figcaption>Skew animation. The x direction</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*CiqnmReO-cFY0SVoGPpxQA.png" /><figcaption>Skew animation. Both x and y directions</figcaption></figure><h4>I.2- Tween&lt;Offset&gt; : Translation Animation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*yk2tVWVFUMJAq__P-ohsrg.gif" /><figcaption>GIF 4: Different types of Translation animation</figcaption></figure><p><strong>1- Offset Translation:</strong></p><p>Tween&lt;Offset&gt; is used to animate translation. There are four widgets used to animate translation:</p><ul><li>FractionalTranslation widget:<br>The translation is expressed as a Offset scaled to the child’s size. For example, an Offset with a dx of 1 (or -1) will result in a horizontal translation equals to the width of the child (or equals to minus the width of the child).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*rE9ROW-LoWnuiui1m4x0dA.png" /><figcaption>Translation animation using FractionalTranslation. form minus the width of the child to the plus the width of the child</figcaption></figure><ul><li>Transform.translate widget:<br>The offset argument specifies the translation in pixels.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/348/1*zYfGK4hiYv31X4EDbzpFpg.png" /><figcaption>Translation animation using Transform.translate.</figcaption></figure><ul><li>SlideTransition widget:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*8EZKtTqhQWjRokepbKocIQ.png" /><figcaption>Translation animation using SlideTransition</figcaption></figure><ul><li>Transform widget</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/434/1*cPPkj2_Gw29yTxpRyg76fQ.png" /><figcaption>Translation animation using Transform widget. horizontal translation form -50 to +50 pixels</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/424/1*2I64rdNdavxvUlcr2YRraw.png" /><figcaption>Translation animation using Transform widget. horizontal translation form -50 to +100 pixels</figcaption></figure><p>For most practical cases animate translation with FractionalTranslation widget is the best choice.</p><p><strong>3- Changing the direction of translation:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*Yio5R_Ojw2M_DCBuxuXpyw.png" /><figcaption>Translation animation form (-0.5,-0.5) to (0.5,0.5)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/407/1*g068hknjRWf4HBswHzEEKA.png" /><figcaption>Translation animation form (0,-0.5) to (0,0.5)</figcaption></figure><p><strong>4- Translation animation. Changing curves:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/387/1*JtxkLmJ6HTnyKMfUUQEc_A.png" /></figure><p><strong>5- Translation animation using Transform widget. combining multiple animation</strong></p><p>With the default Transform constructor you can combine rotation, scale and translate and many other type of animation with one Tween&lt;double&gt;.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/441/1*YZkahDXWvbPJmc9CWm_t5A.png" /><figcaption>Combining translation and rotation animation using Transform Widget</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/446/1*PV_H7fZj6939jF75cIauEA.png" /><figcaption>Combining translation, rotation and scaling animation using Transform Widget</figcaption></figure><p>That’s enough for one tween animation for the article. In the next article I will go through: IntTween, StepTween, AlignmentTween, AlignmentGeometryTween, EdgeInsetsTween , EdgeInsetsGeometryTween, FractionalOffsetTween, BorderTween, BorderRadiusTween, ShapeBorderTween, DecorationTween, BoxConstraintsTween, RectTween, TextStyleTween and ThemeDataTween.</p><h3>I- Multi Tweens Animation:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*9_6LvODTv-Kz5OD5rNAJ5Q.gif" /><figcaption>GIF 5: Multi tweens animation</figcaption></figure><p>If your animation needs to use multi tweens with different type, Animator has a very easy solution. tweenMap and builderMap argument of Animator are the solution.</p><p><strong>1- Two tweens: Opacity + Translation:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/1*p4XGA7BA0_11Y4wbLDxO4g.png" /><figcaption>Two tweens: Opacity + Translation</figcaption></figure><p>tweenMap argument is a Map&lt;String, Tween&gt;. Keys are your name of the animation, and values are Tweens of any type.</p><p>The builderMap is of type Function(Map&lt;String, Animation&gt;) -&gt; Widget. Wherever you want a particular type of animation, use the corresponding key to call it.</p><p>There is no limit on the number of Tweens to use.</p><p><strong>2 - Three tweens: Opacity + Translation + Rotation:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/524/1*s_aOXIV5OCtnMfdFvtAj_g.png" /><figcaption>Three tweens: Opacity + Translation + Rotation</figcaption></figure><p><strong>3- Four tweens: Opacity + Translation + Rotation + Color:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/1*vMlpi1O9o7RK3GWZEBcZpw.png" /></figure><p><strong>4- Five tweens: Opacity + Translation + Rotation + Color + Scaling:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/517/1*SOagRd_QbINZEPKhCFRMmw.png" /></figure><p><strong>Conclusion:</strong></p><p>Animator has an argument called <strong>endAnimationListener</strong>. It takes a VoidCallback function to be executed when animation is finished. One use of this argument is to trigger another animation once the actual animation is finished. The GIF bellow used this argument to produce a animation of all the animations we covered in this article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*5b9-MVbRyhDIS6xm92Qxpg.gif" /></figure><p>To better see the animation, hit this <a href="https://twitter.com/MELLATIM/status/1105742376335749121">link</a>.</p><p>The source code of this animation is<a href="https://github.com/GIfatahTH/animator/tree/master/example"> here</a>.</p><p><a href="https://twitter.com/FlutterComm">JavaScript is not available.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e378e82b2508" width="1" height="1" alt=""><hr><p><a href="https://medium.com/flutter-community/flutter-animation-has-never-been-easier-part-1-e378e82b2508">Flutter Animation has Never Been Easier — Part 1</a> was originally published in <a href="https://medium.com/flutter-community">Flutter Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter #OneYearChallenge; scoped_model vs BloC_pattern vs states_rebuilder]]></title>
            <link>https://medium.com/flutter-community/flutter-oneyearchallenge-scoped-model-vs-bloc-pattern-vs-states-rebuilder-23ba11813a4f?source=rss-818757b53c98------2</link>
            <guid isPermaLink="false">https://medium.com/p/23ba11813a4f</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[dark]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[MELLATI Fatah]]></dc:creator>
            <pubDate>Mon, 25 Feb 2019 12:01:02 GMT</pubDate>
            <atom:updated>2019-12-07T13:14:52.278Z</atom:updated>
            <content:encoded><![CDATA[<h3>Flutter #OneYearChallenge; Scoped Model vs BloC Pattern vs States Rebuilder</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*np5KNt2efsHDw3sE5tvFxw.png" /></figure><p>Flutter is <em>declarative</em>. This means that Flutter rebuilds its user interface (UI) from scratch to reflect the current state of your app each time <em>setState()</em> method is called. But what is a state? Roughly speaking, a state is the actual values of variables the app has in memory. State management is a set of techniques used to make the UI display the current state, and auto update if the state changes. In Flutter, state management techniques differ in: <strong>How</strong>, <strong>Where </strong>and <strong>when </strong>to call <em>setState()</em>.</p><p>This article answers these How-Where-When questions for three techniques: scoped_model, BloC_pattern and states_rebuilder.</p><p>To put these three state management techniques under test, and to see how much the difference in the answer of the How-Where-When question impact the performance of these techniques, I choose to challenge them.</p><h3>The challenge:</h3><p>The UI of the challenging app consists of a <strong>horizontal ListView</strong> of counter <strong>itemCards</strong>. When the user taps on any <strong>itemCard </strong>from the <strong>ListView</strong>, a card appears in the detailed container under the <strong>ListView </strong>with the same color and count number.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/1*Wx6FK1acPIp4S3a5YMXzqg.png" /><figcaption>UI of the challenge</figcaption></figure><p>The tricky part of the challenge is that if the user taps on the detailed container, the detailed counter is incremented and only the corresponding <strong>itemCard </strong>that has been topped in the <strong>ListView </strong>rebuilds to show the new counter value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*RUTLQJmX7Dk4z6K4Y7GwKQ.png" /><figcaption>Detailed container is tapped 5 times</figcaption></figure><p>The <strong>itemCard </strong>are randomly colored to track the rebuild of each card because if any card rebuilds the random color changes.</p><p>This challenge is tricky because as I said Flutter is declarative and don’t have something like findViewByID. For Frameworks that have something like this, the challenge is easily done by imperatively finding the itemCard of particular ID and increment its counter, but for Flutter, it is not that easy.</p><p>Let’s give the microphone to the three state management techniques to speak about themselves.</p><h3>Scoped_model:</h3><p><strong>Update note (Dec-2019): scoped_model </strong>is deprecated in favor of the <a href="https://pub.dev/packages/provider">provider </a>package. But the <strong>provider </strong>package is more about dependency injection than state management. Nevertheless, the state management philosophy of the provider is similar to that of the <strong>scoped_model</strong>.</p><p>Hi my name is scoped_model, I’m a library that helps you handling data in your application to achieve neat separation of your logic form UI. I’m very happy that flutter team has recently dedicated to me an entire section in the official documentation. My uncle <a href="https://steemit.com/utopian-io/@tensor/managing-state-with-the-scoped-model-pattern-in-dart-s-flutter-framework">Tensor Programming</a> told me that I was originated as a pattern found in Google’s Fuchsia OS repository. Also, he told me that Fuchsia used of Flutter in many of its native widgets and my pattern is used heavily in those widgets to manger their state.</p><h4>How to use me?</h4><p>To implement me! It is the easiest thing in the world. Just remember this: I have three classes and you have three steps.</p><p>I have three classes: <strong>Model</strong>, <strong>ScopedModel</strong>, <strong>ScopedModelDescendant.</strong></p><p>You follow three steps:</p><p>1- Your logic class, <em>YourModel</em>, must extend my Model class. You have to do so to be able to call my <em>notifyListeners()</em> inside any of <em>yourMethods</em>.</p><p>This is a typical implementation of my Model: (after importing me!):</p><pre><strong>//scoped_model:</strong><br>class <strong><em>YourModel </em></strong>extends <strong>Model </strong>{</pre><pre> Var <strong><em>yourVar</em></strong>;</pre><pre> <strong><em>yourMethod</em></strong>(){</pre><pre>   // some logic staff;<br>   <strong><em>yourVar </em></strong><em>= yourNewValue;<br></em>   <strong>notifyListeners</strong>(); // this is my method. Call it to update widgets</pre><pre> }<br>}</pre><pre><strong>// Update:Dec-2019<br>// provider:<br></strong>class <strong><em>YourModel </em></strong>extends <strong>ChangeNotifier</strong>{</pre><pre>Var <strong><em>yourVar</em></strong>;</pre><pre><strong><em>yourMethod</em></strong>(){</pre><pre>// some logic staff;<br>   <strong><em>yourVar </em></strong><em>= yourNewValue;<br></em>   <strong>notifyListeners</strong>(); // this is my method. Call it to update widgets</pre><pre> }<br>}</pre><p>2- In your UI part, wrap the top most widget that you want to make it as well as its children have access to <em>YourModel </em>class with <strong>ScopedModel</strong>:</p><pre><strong>//scoped_model<br>ScopedModel</strong>(<br> model: <strong><em>YourModel</em></strong>(), <br> child : <strong><em>TopWidget</em></strong>()<br>) // wrong </pre><pre><strong>// Update:Dec-2019<br></strong>//provider<br><strong>ChangeNotifierProvider</strong>(<br> create: ()=&gt; <strong><em>YourModel</em></strong>(), <br> child : <strong><em>TopWidget</em></strong>()<br>) // Accepted because provider can infer the type</pre><p>Oops! This is a common error beginners often do. It’s important to not forget to specify the generic type of your model:</p><pre>//scoped_model<strong><br>ScopedModel</strong>&lt;<strong><em>YourModel</em></strong>&gt;(<br> model: <strong><em>YourModel</em></strong>(), <br> child : <strong><em>TopWidget</em></strong>()<br>)</pre><pre><strong>// Update:Dec-2019<br></strong>//provider<br><strong>ChangeNotifierProvider</strong>&lt;<strong><em>YourModel</em></strong>&gt;(<br> create: ()=&gt; <strong><em>YourModel</em></strong>(), <br> child : <strong><em>TopWidget</em></strong>()<br>)</pre><p>2- Now in any of your widgets underneath the <em>TopWidget </em>and whenever you want to access <em>YourModel </em>and want the widget to be rebuilt <em>after calling notifyListeners</em>(), wrap this widget in<strong> ScopedModelDescendant</strong></p><pre><strong>//scoped_model<br>ScopedModelDescendant</strong>&lt;<strong><em>YourModel</em></strong>&gt;(<br>  builder: (BuildContext context,widget child,<strong>YourModel yourModel</strong>) {<br>    <em>return </em><strong><em>ChildWidget</em></strong>(<strong><em>yourModel</em></strong><em>.</em><strong><em>yourVar</em></strong>);<br>   }<br>)</pre><pre><strong>// Update:Dec-2019<br></strong>//provider<br><strong>Consumer</strong>&lt;<strong><em>YourModel</em></strong>&gt;(<br>  builder: (BuildContext context,<strong>YourModel yourModel</strong>,Widget child) {<br>    <em>return </em><strong><em>ChildWidget</em></strong>(<strong><em>yourModel</em></strong><em>.</em><strong><em>yourVar</em></strong>);<br>   }<br>)</pre><p>Again do not forget to specify the generic type.</p><p>That all, I have three classes you follow three steps, and your app is reactive.</p><p>Note: In case you want to access <em>YourModel </em>but don’t want the widget form where you get access to be rebuilt each time <strong>notifyListeners</strong>() is executed, for example when you want to call a method from <em>YourModel</em>, use:</p><pre><strong>//scoped_model<br>ScopedModel</strong>.of&lt;<strong><em>YourModel</em></strong>&gt;(context).<strong><em>yourMethod</em></strong>();</pre><pre><strong>// Update:Dec-2019<br></strong>//provider<br><strong>Provider</strong>.of&lt;<strong><em>YourModel</em></strong>&gt;(context, listen: false).<strong><em>yourMethod</em></strong>();</pre><p>As many of you may know it before, you can get the same result as the above line of code with <strong><em>ScopedModelDescendant </em></strong>provided you set the optional parameter <strong><em>rebuildOnChange </em></strong>to false.</p><pre><strong>ScopedModelDescendant</strong>&lt;<strong><em>YourModel</em></strong>&gt;(<br>   <strong>rebuildOnChange </strong>: false,<br>   builder: (context,child,<strong>yourModel</strong>) {<br>    <strong>yourModel</strong>.<strong><em>yourMethod</em></strong>();<br>   }<br>)</pre><h4>How do I manage the state?</h4><p>In the first step above, you extend <em>YourModel </em>with <strong>Model </strong>class. Behind the scenes, there is a <strong>Set </strong>of <strong>VoidCallback</strong>. Whenever you call <strong>notifyListeners(), </strong>the program iterates inside the <strong>Set </strong>and executes these <strong>VoidCallbacks</strong>. A <strong>voidCallback</strong> is<strong> </strong>nothing than <strong>(){setState();}</strong>. The question is: Where the <strong>voidCallbacks </strong>have been added to the <strong>Set</strong>. the answer in the second step.</p><p>In the second step, you use <strong>ScopedModel </strong>class to wrap the top most widget of your tree. The <strong>ScopedModel </strong>has two missions:</p><p>1- Under the hood, it uses the <strong>AnimatedWidget </strong>which is a StatefulWidget. In the <strong>initState </strong>of the <strong>AnimatedWidget</strong>, the <strong>VoidCallback </strong>is added to the <strong>Set.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*aypXTGGTYN5gxEC6q6RKYw.png" /><figcaption>addListener method adds a VoidCallback(_handleChage) to the Set.</figcaption></figure><p>Now when you call <strong>notifyListeners(), </strong>your <em>TopWidget </em>is rebuilt. Do all the child widgets rebuild with <em>TopWidget? NO, It is the </em><strong>InheritedWidget!!!</strong></p><p>2- The second mission of the <strong>ScopedModel </strong>is to make use of the <strong>InheritedWidget </strong>to provide <em>YourModel </em>to all descendant Widgets. An important feature of the <strong>InheritedWidget </strong>is that it stops the down propagation of the rebuild process. Only widgets that inherit from it using <strong><em>inheritFromWidgetOfExactType </em></strong>method will be rebuilt.<strong> </strong>The question is how to inherit form the<strong> InheritedWidget? </strong>the answer in the third step.</p><p>3- The role of <strong>ScopedModelDescendant </strong>is to make use of the <strong><em>ScopetModel.of(context)</em></strong> method to obtain <em>YourModel </em>instance, and if the <em>rebuildOnChange </em>is set to true, which is the default value, the wrapped widget will be attached to the <strong>InheritedWidget </strong>and will be notified to rebuild.</p><h4>To the challenge</h4><p>1- The logic part:</p><p>The MainModel class has four fields and three methods:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dbd08a6330ac494ac287ea4b23faa7fb/href">https://medium.com/media/dbd08a6330ac494ac287ea4b23faa7fb/href</a></iframe><p>The variables are:</p><p><strong>itemProvider:</strong> has all the methods related to fetching items from external providers;<br><strong>items </strong>: a list of Item objects that will be displayed in the ListView;<br><strong>detailedColor </strong>: is the color of the card shown in the detailed container; and<br><strong>detailedIndex </strong>: is the index of the card shown in the detailed container.</p><p>The methods are:</p><p><strong>getItems()</strong> : It is called from the initState to fetch on the items from the itemProvider and after getting them it calls notifyLisners();<br><strong>shwDetailed(Color color, int index):</strong> It is called when the user taps on a card from the ListView. It is called with the tapped color and index. Then it mutate the detailedColor and detailedIndex and call notifyListeners() to rebuild the detailed container;<br><strong>increment() : </strong>called when the user taps on the detained container to increment the counter of the item that have an index equal to detailedIndex.</p><p>This is all for the MainModel class.</p><p>2- The UI part:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c3ff4bd4665ba809093d8ca4d5a3805/href">https://medium.com/media/5c3ff4bd4665ba809093d8ca4d5a3805/href</a></iframe><p>lines 15–18 : instantiation of <strong>ScopedModel</strong>;<br>line 35 : calling the <strong>getItems()</strong> from the <strong>initState </strong>to fetch form items;</p><p>lines 45–68 : <strong>ScopedModelDescendant </strong>is defined to make the horizontal ListView reactive:<br> — — — line 46 : check if items List is null, then show a circular progress indicator, if not null show the ListView;<br> — — — lines 54–55 : for each card get a random color. each time the ListView is rebuilt the colors change randomly;<br> — — — lines 58–64 : <strong>ItemCard </strong>is a stateless widget to display a card;<br> — — — lines 61–62 : call of the <strong>showDetailed(randColor, index)</strong> when a card is tapped;</p><p>lines 71–84 : <strong>ScopedModelDescendant </strong>is defined to make the detailed container reactive:<br> — — — lines78–81 : display the card that has an index equals to <strong>detailedIndex</strong> and call <strong>increment()</strong> method when the detailed container is tapped.</p><p>And this is the end of the UI part. this is a GIF of the app:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*aNqF6HyB5Mn42pQ3qkUQgA.gif" /></figure><p>As you can see, in the first 10 seconds when a card from the ListView is tapped the whole ListView as well as the detailed container are rebuilt (witnessed by the random colors change). This behavior is not expected. we don’t want the ListView to rebuild when any of its itemCard is tapped. This side effect is understood, because the rebuild process in the scoped model is controlled by the InheritedWidget which rebuilds any widget that inherit from it using <strong><em>inheritFromWidgetOfExactType,</em></strong><em> and this is the case for the ListView and the detailed container.</em></p><p>Perhaps one can think of switching the <strong><em>rebuildOnChange </em></strong><em>parameter in </em><strong>ScopedModelDescendant </strong>to false, but then, at the start of the app when data are fetched the ListView will not rebuild and the app stay stacked in the circular progress indicator.</p><p>When it comes to the challenge the scoped model fails to increment the card count without rebuilding the whole ListView.</p><h4>In conclusion:</h4><p>If your app is small, let’s say you have one task to go from A to B, with scoped_model you do it straightforward with some undesired side effect. The picture below schematized the one task app with straight filled arrow and dash arrow for the undesired rebuild.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/269/1*bYBx8_oRowXl2UuJPA2fcg.png" /><figcaption>schematic of one task simple app</figcaption></figure><p>The dashed arrow means that for small app, the rebuild of non-wanted widget is controlled by setting <strong><em>rebuildOnChange</em> </strong>to false<strong><em>.</em></strong></p><p>But when it comes to more complex apps, the undesired rebuild is inevitable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/245/1*a1JPE8npJ0FsJY7YXMWf2g.png" /><figcaption>schematic of 5 tasks complex app</figcaption></figure><p>The solid curved arrows are the inevitable side effects of rebuilding widgets we want them not to rebuild.</p><p>The scooped_model is declared losing the challenge with unexpected side effects.</p><p><strong>Note</strong>: It is worth noting that the team behind scoped_model are working for a replacement of the scoped_model by other one named Provider. The backend idea of calling setState() inside AnimatedWidget and relaying on InheritedWideget to rebuild the widgets that inherited from it, is the same. From first judgement, the shortcoming mentioned for the original scoped_model is still relevant with the new Provider approach, because the latter always relays on InheritedWidget to manage widgets rebuild.</p><h3>BloC Pattern</h3><p>Hi, my name is Business Logic Component and my friends call me BloC. I’m a state management system for Flutter recommended by Google developers. I help you centralize your data and logic and give you the ability to access them from any widget in your UI. My parents are Cong Hui, Paolo Soares, and Wenfan Huang from Google. They conceived me to get the maximum code sharing between Flutter and AngularDart.</p><h4>How to use me?</h4><p>Do you know what is a stream? If yes, then you are in a good point to start using me. If no, I try to give you some basic information about streams.</p><p>Think of a stream as pipe filled with water that flows from the A side to the B side. Let’s say you are in side A and want to send some colorful tiny children’s balls to side B. You sink these balls one after the another inside the pipe and the water will transport them to side B one by one in a stream fashion. The balls exit the pipe from B side. Let’s say they fall and make a noise. Let’s say there is another person inside B waiting for the balls. Because this person doesn’t know when exactly a ball arrives, he decided to read a newspaper. It’s only when he listens the sound of a ball that he is aware of the arrival of a ball. At that time, he can catch the ball and make use of it.</p><p>In real BloC, the pipe is <strong>StreamController</strong>, the flow of water is <strong>StreamController.stram</strong>, the action of pushing balls from side A is <strong>StreamController.sink</strong>, colorful children’s balls are <strong>data </strong>of any type, and the person in the B side listening to ball falling is <strong>StreamController.stram.listen</strong>.</p><p>Enough of analogy. In Dart document you read about <strong>StreamController</strong>:</p><blockquote>This controller (StreamController<strong>)</strong> allows sending data, error and done events on its <a href="https://api.dartlang.org/stable/2.1.0/dart-async/StreamController/stream.html">stream</a>. This class can be used to create a simple stream that others can listen on, and to push events to that stream.</blockquote><p>To implement me, for each of your variables you need to define five things:</p><p>1- Your variable name; (not necessary if you use rxDart)<br>2- StreamController;<br>3- stream<br>4- sink;<br>5- Close StreamController.</p><p>This is how a typical bloc class should look like:</p><pre>class <strong>YourBloc </strong>{</pre><pre>  var <strong>yourVar</strong>;</pre><pre>  final <strong>yourVarController </strong>= <strong>StreamController</strong>&lt;yourType&gt;();</pre><pre>  Stream&lt;<strong>yourType</strong>&gt; get <strong>yourVarStream </strong>=&gt; <strong>counterController.stream</strong>;</pre><pre>  StreamSink&lt;<strong>yourType</strong>&gt; get <strong>yourVarSink </strong>=&gt; <strong>counterController.sink</strong>;</pre><pre>  yourMethod() {</pre><pre>    // some logic staff;<br>    <strong><em>yourVar </em></strong><em>= yourNewValue;<br>   </em><strong><em> </em>yourVarSink.add(<em>yourVar</em>)</strong>;<br> }</pre><pre>  dispose() {<br>   <strong>yourVarController.close()</strong>;<br>  }<br>}</pre><p>This is only basic. The StreamController, you used above, is for one single subscriber (listener). If you want to listen to the same stream many times you have to use StreamController.broadcast.</p><p>BloC pattern is often used with the third party library RxDart because it has many features not available in the standard dart StreamController.</p><p>To use RxDart, be careful of the naming convention. <strong>StreamController </strong>in dart becomes <strong>Subject </strong>in RxDart, <strong>Stream </strong>in dart are <strong>Observable </strong>in Rx and <strong>listen </strong>in dart is <strong>subscribe </strong>in RxDart.</p><p>To get the same functionality as <strong>StreamController.broadcast&lt;T&gt;</strong>, use <strong>PublishSubject&lt;T&gt;</strong> class in RxDart. But if you want any new listener to get the latest value add to the stream use <strong>BehaviorSubject&lt;T&gt;</strong> class.</p><p>I’m sure beginners find me a little complicated. But whenever they are used to me, they will love me.</p><p>I’m hearing some of you complaining form the amount of boilerplate you have to use to make a simple app reactive. Even my co-creator Paolo Soares is not happy with that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*wrffE8vGRywSLEgcHS3FZw.png" /><figcaption><a href="https://twitter.com/paolo_soares/status/1089966367833509888">https://twitter.com/paolo_soares/status/1089966367833509888</a></figcaption></figure><p>But, again, I’m certain that when it comes to more complex apps, I am the best choice.</p><h4>How do I manage the state?</h4><p>I manage the state with the help of <strong>StreamBuilder </strong>which extent a <strong>StatefulWidget </strong>named <strong>_StreamBuilderBase</strong>.</p><p>Inside the initState of <strong>StreamBuilderBaseState</strong>, I start listening to the stream you have provided in the “<strong>stream” </strong>parameter, and execute the setState() whenever the stream received data to rebuild my child widgets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/434/1*-61bcgTPkV8hegIm_7usRw.png" /><figcaption>Part of _StreamBuilderBaseState class where setState() is called</figcaption></figure><h4>To the challenge</h4><p>1- The logic part:</p><p>As in the scoped model case, in the logic we need four variables and three methods:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5939343bfca303cb78af6946c23998c8/href">https://medium.com/media/5939343bfca303cb78af6946c23998c8/href</a></iframe><p>The idea is that for each variable that we want use it in the UI, we need to define up to four fields.</p><p>The variables are:</p><p><strong>itemProvider:</strong> has all the methods related to fetching items from external providers; (this variable will not be used in the UI);<br><strong>items </strong>: is a list of Items. We want to use it in the UI, also we want to mutate it form the BloC. For this reason, we need to define four fields: (<em>_items</em>, <em>itemsConroller</em><strong>, </strong><em>itemsStream</em><strong>, </strong><em>itemsSink</em><strong>):</strong></p><ul><li>List&lt;Item&gt; <em>_items</em>;</li><li><em>itemsConroller </em>= <strong>StreamController</strong>&lt;List&lt;Item&gt;&gt;.();</li><li><strong>Stream </strong>get <em>itemsStream </em>=&gt; itemsConroller.<strong>stream</strong>;</li><li><strong>StreamSink</strong>&lt;List&lt;Item&gt;&gt; get <em>itemsSink </em>=&gt; itemsConroller.<strong>sink</strong>;</li></ul><p><strong>detailedColor </strong>: is the color of the card shown in the detailed container. So we want to use it in the UI, but we don’t want to mutate it in the BloC. for this reason, we need three fields: (<em>detailedColorConroller, detailedColorStream, detailedColorSink</em>):</p><ul><li>detailedColorConroller = <strong>StreamController</strong>&lt;Color&gt;();</li><li><strong>Stream </strong>get detailedColorStream =&gt; detailedColorConroller.<strong>stream</strong>;</li><li><strong>StreamSink</strong>&lt;Color&gt; get detailedColorSink =&gt; detailedColorConroller.<strong>sink</strong>;</li></ul><p><strong>detailedIndex </strong>: is the index of the card shown in the detailed container. So we want to use it in the UI, but we don’t want to mutate it in the BloC. for this reason, we need three fields: (<em>detailedItemConroller, detailedItemStream, detailedItemSink</em>):</p><ul><li>final <em>detailedItemConroller </em>= <strong>StreamController</strong>&lt;Item&gt;();</li><li><strong>Stream </strong>get <em>detailedItemStream </em>=&gt; detailedItemConroller.<strong>stream</strong>;</li><li><strong>StreamSink</strong>&lt;Item&gt; get <em>detailedItemSink </em>=&gt; detailedItemConroller.<strong>sink</strong>;</li></ul><p>Do not forget to close all the StreamControllers.</p><p>The methods are:</p><p><strong>getItems()</strong> : It is called from the initState to fetch on the items from the itemProvider and after getting them it calls itemsSink.add(_items) to rebuild the StreamBuilder that is listening to the <em>itemsStream</em>;<br><strong>shwDetailed</strong> <strong>(Color color, int index, Item item):</strong> It is called when the user tapped on a card from the ListView. It is called with the tapped color, index and item. It call detailedColorSink.add(color) and detailedItemSink.add(item) to rebuild the StreamBuilders that are listening to them and save the provided index in a private variable _detailedIndex to be used to in the increment method;<br><strong>increment() : </strong>called when the user taps on the detained container to increment the counter of the item that have an index equal to _detailedIndex. that it calls itemsSink.add(_items) to rebuild the ListView and detailedItemSink.add(_items[_detailedIndex]) to rebuild the detailed container;</p><p>To get to this code I passed through many try and error process and many error fixing.</p><p>2- The UI part:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/227eac35b422769ffc16fe4824c1482c/href">https://medium.com/media/227eac35b422769ffc16fe4824c1482c/href</a></iframe><p>lines 22–46 : StreamBuilder of the item list.<br> — — — line 23 : listening to itemsStream,<br> — — — line 24 : cheking if snapshot don’t has data to show the circular progress indicator, or if it has data to show the ListView.<br> lines 53–67 : StreamBuilder of the detailed item.<br> — — — line 53–67 : nested StreamBuilder for the detailed color.</p><p>this is a GIF of the app with BloC pattern:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*ZFFDk8Odw8qTiEePqLV68Q.gif" /></figure><p>In contrast to scoped_model, when a card from the ListView is tapped the ListView does not rebuild. This is a point in favor ofthe BloC pattern. But the BloC does not pass the challenge because it fails to increment the card count without rebuilding the whole ListView. I can say that we can no do that, but if there is a way to pass the challenge it would be very complicated.</p><h4>In conclusion:</h4><p>For small app, the BloC pattern tends to complicate the uncomplicated. For one task app, let’s say to move from A to B, you have to define a StreamController, a stream, a sink and dispose the StreamController.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/1*ZFaCv5R1oqVt2VYUEof_lQ.png" /></figure><p>When it comes to more complex app, the situation is worse especially if you constrain yourself to use only streams.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/338/1*TPiKjNYMPvau9mlhR5sGeA.png" /><figcaption>schematic representation of multi task complex app in BloC pattern</figcaption></figure><h3>States_rebuilder</h3><p><strong>Update note (Dec-2019): states_ rebuilder</strong> know has what is called explicit reactivity and implicit reactivity. Explicit reactivity means that you have to make your logic class to extend <strong>StatesRebuilder </strong>and to explicitly notify listeners using <strong>rebuildStates </strong>method. In Implicit reactivity, your model is a pure dart class without any extension of whatsoever. It is the duty of the library to add reactivity for you, thus, leaving your model clear, simple, testable, maintainable, and framework independent.</p><p><a href="https://pub.dartlang.org/packages/states_rebuilder">states_rebuilder | Flutter Package</a></p><p>Hi there, my name is states_rebuilder, almost all of you don’t know me. It is very difficult for newcomers to have a place in the flutter state management field with the presence of scoped_model, BloC, Redux, and many other third libraries. But anyway I’ll try.</p><p>My creator is MELLATI, the author of this article. He wrote three articles about state management in flutter to introduce me. (<a href="https://medium.com/flutter-community/flutter-state-management-setstate-fn-is-the-easiest-and-the-most-powerful-44703c97f035">article 1</a>, <a href="https://medium.com/flutter-community/flutter-state-management-has-never-been-easier-think-statelessly-then-add-reactivity-d30c75760da0">article 2</a>, <a href="https://medium.com/flutter-community/flutter-and-web-code-sharing-a-state-management-demo-2e615d3f2b1a">article 3</a>).</p><h4>How to use me?</h4><p>I am the simplest state management technique to implement. Do not believe me? Just follow me.</p><p>Before going through steps of implementation, I have to point out something important. Sometimes getting new ideas is easier than baptizing it. That exactly what happened to me. I have three choices to name my logic classes:</p><p>1- BloC, but this often confused with the BloC pattern which is based on streams;<br>2- Model as in scoped_model, but this confuses me. Model has another meaning in MVC, MVP, and MVVM popular design patterns;<br>3- ViewModel, I think is the most suitable term because what The ViewModel does in MVVM is to store states, mutate states, and expose change events when the states change to update the view.</p><p>But BloC is a fancy word and I like it. So I’ll use it provided you don’t think of streams anymore.</p><p>OK, to implement me remember: I have two classes and you have two steps:</p><p>I have two classes: <strong>StatesRebuilder </strong>and <strong>StateBuilder</strong>, you follow two steps:</p><p>1- Your logic class, <strong>YourBloc</strong>, must extend my <strong>StatesRebuilder </strong>class to be able to use my <strong>rebuildStates </strong>method:</p><p>This is a typical implementation of my <strong>StatesRebuilder</strong>:</p><pre>Import &quot;states_rebuilder/states_rebuilder.dart&quot;;</pre><pre><strong>1- Explict reactivity:</strong></pre><pre>class <strong>YourBloc </strong>{</pre><pre> var <strong>yourVar</strong>;</pre><pre> /// You have two alternatives:<br><strong><em> /// First alternative : Notify all listeners</em></strong></pre><pre> <strong>yourMethod1</strong>() {</pre><pre>   // some logic staff;<br>   <strong>yourVar </strong>= yourNewValue;</pre><pre><strong>   rebuildStates</strong>();<br> }</pre><pre><strong><em> // Second alternative (tag alternative): filter notification by tag</em></strong></pre><pre><strong>yourMethod2</strong>() {</pre><pre> // some logic staff;<br>   <strong>yourVar </strong>= yourNewValue;</pre><pre><strong>rebuildStates</strong>([“<strong>yourStateTag1</strong>”, “<strong>yourStateTag2</strong>”]);<br> }<br>}</pre><pre><strong>// Update:Dec-2019 </strong><br><strong>2- Implicit reactivity:<br>A pure vanilla dart class without extantion or notification.</strong></pre><pre>class <strong>YourBloc </strong>{</pre><pre>var <strong>yourVar</strong>;</pre><pre><strong>yourMethod1</strong>() {</pre><pre>  // some logic staff;<br>  <strong>yourVar </strong>= yourNewValue;<br> }<br>}</pre><p><strong>rebuildStates </strong>method is equivalent to <strong>notifyListeners </strong>in the <strong>scoped_model</strong>.</p><p>As you can see, you have two alternatives to call the <strong>rebuildStates </strong>method:</p><ul><li>The first alternative (notify all listeners): When rebuildStates is called without arguments it will notify all listener widgets.</li><li>The second alternative (or the tag alternative): in the UI you define tags to the widgets that you want to be rebuilt from the BloCs. In <strong>yourMethod </strong>you call the <strong>rebuildStates </strong>with any number of tags you want. (<strong>rebuildStates</strong>([“<strong>yourStateTag1</strong>”, “<strong>yourStatetTag2</strong>”]); )</li></ul><p>The question is: How to add tags to widgets? The answer is in the next step.</p><p>2- In your UI and after providing your blocs, wrap any widget you want to be able to rebuild from the BloC with <strong>Statebuilder </strong>wiget, give it a tag and define the list of models you want to use the tag from. This is the first alternative:</p><pre><strong>StateBuilder</strong>(<br>  models : [yourBloc]<br>  tag: “<strong>yourStateTag1</strong>”, // tag is optional<br>  builder: (_,__) =&gt; <strong>YourChildWidget</strong>(<strong>yourBloc</strong>.<strong>yourVar</strong>),<br>)</pre><p>With this, you can call <strong>yourMethod1 </strong>from any place in the UI to rebuild the <strong>YourChildWidget</strong>.</p><p>For example, in another place in your UI even from another file, you can have:</p><pre>RaisedButton(<br>  ..<br>  onPressed : <strong>yourBloc</strong>.<strong>yourMethod1</strong>,<br>)</pre><p><strong>tag </strong>parameter is optional and can be omitted. In this case, the widget will be notified using <strong>rebuildStates() </strong>without arguments.</p><p><strong>states_rebuilder </strong>creates a default tag to each <strong>StateBuilder </strong>widget which is the <strong>BuildContext </strong>of the widget.</p><pre><strong>StateBuilder</strong>(<br>   models : [yourBloc]<br>   builder: (<strong>BuildContext context, _</strong>) =&gt; <strong>YourChildWidget</strong>(<br>        //context is the default tag<br>        <strong>yourBloc</strong>.<strong>yourVar</strong>,<br>        onPressed: ()=&gt;<strong>yourBloc.yourMethod2</strong>(<strong>context</strong>),<br>     ),<br>)</pre><p>The default tag is very useful if you are to render a list of widgets using <strong>ListView </strong>or any similar widget. Imagine you have 100 <strong>ListTiles</strong>, it’s not practical to give them all tags. This gives you the ability to rebuild any of these 100 L<strong>istTiles </strong>from the blocs without rebuilding the whole ListView (see the challenge section).</p><p><strong>StateBuilder </strong>offers more options to use. This is the class constructor:</p><pre><strong>StateBuilder&lt;T&gt;</strong>(<br> <strong>onSetState</strong>: (BuildContext context, ReactiveModel&lt;T&gt; model){<br>  /*<br>   Side effects to be executed after sending notification and before    rebuilding the observers. Side effects are navigating, opening the drawer, showing snackBar,...<br>*/<br> },</pre><pre><strong>onRebuildState</strong>: (BuildContext context, ReactiveModel&lt;T&gt; model){<br> // The same as in onSetState but called after the end rebuild process.<br>},</pre><pre><strong>initState</strong>: (BuildContext context, ReactiveModel&lt;T&gt; model){<br>// Function to execute in initState of the state.<br>},</pre><pre><strong>dispose</strong>: (BuildContext context, ReactiveModel&lt;T&gt; model){<br>// Function to execute in dispose of the state.<br>},</pre><pre><strong>didChangeDependencies</strong>: (BuildContext context, ReactiveModel&lt;T&gt; model){<br>// Function to be executed  when a dependency of state changes.<br>},</pre><pre><strong>didUpdateWidget</strong>: (BuildContext context, ReactiveModel&lt;T&gt; model, StateBuilder oldWidget){<br>// Called whenever the widget configuration changes.<br>},</pre><pre><strong>afterInitialBuild</strong>: (BuildContext context, ReactiveModel&lt;T&gt; model){<br>// Called after the widget is first inserted in the widget tree.<br>},</pre><pre><strong>afterRebuild</strong>: (BuildContext context, ReactiveModel&lt;T&gt; model){<br>/*<br>Called after each rebuild of the widget. The difference between onRebuildState and afterRebuild is that the latter is called each time the widget rebuilds, regardless of the origin of the rebuild. Whereas onRebuildState is called only after rebuilds after notifications from the models to which the widget is subscribed.<br>*/<br>},</pre><pre>// If true all model will be disposed when the widget is removed from the widget tree<br><strong>disposeModels</strong>: true,</pre><pre>// A list of observable objects to which this widget will subscribe.<br><strong>models</strong>: [model1, model2]</pre><pre>// Tag to be used to filer notification from observable classes.<br>// It can be any type of data, but when it is a List,<br>// this widget will be saved with many tags that are the items in the list.</pre><pre><strong>tag:</strong> dynamic</pre><pre><strong>builder</strong>: (BuildContext context, ReactiveModel&lt;T&gt; model){<br>/// [BuildContext] can be used as the default tag of this widget.<br>/// The model is the first instance (model1) in the list of the [models] parameter.<br>/// If the parameter [models] is not provided then the model will be a new reactive instance.<br>},</pre><pre><strong>builderWithChild</strong>: (BuildContext context, ReactiveModel&lt;T&gt; model, Widget child){<br>///Same as [builder], but can take a child widget containing the part of the widget tree that we do not want to rebuild.<br>/// If both [builder] and [builderWithChild] are defined, it will throw.<br>},<br>//The child widget that is used in [builderWithChild].</pre><pre><strong>child</strong>: MyWidget(),<br>)</pre><p><strong>initState, dispose, didChangeDependencies, didUpdateWidget</strong> have the same meaning as in <strong>StatefulWidget</strong>. For example, you can execute some code in the initState to fetch some data from an API. You can pass the tag (context by default) to the bloC to rebuild it when you get the data.</p><pre><strong>StateBuilder</strong>(<br>    initState : (<strong>context,_</strong>) =&gt; <strong>yourBloc</strong>.<strong>yourInitMethod</strong>(<strong>context</strong>),<br>    builder: (_) =&gt; <strong>YourChildWidget</strong>(<br>                <strong>yourBloc</strong>.<strong>yourVar</strong>,<br>             ),<br>)</pre><p>in the BloC you have something like this:</p><pre>class <strong>YourBloc </strong>extends <strong>StatesRebuilder</strong>{</pre><pre>var <strong>yourVar</strong>;</pre><pre><strong>yourInitMethod</strong>(context )async {</pre><pre>   await fetchItemsFromAPI();<br>   <strong>yourVar </strong>= yourNewValue;</pre><pre>   <strong>rebuildStates</strong>([<strong>context</strong>]);<br> }</pre><p><strong>Endnote: </strong>If you followed my last articles you may have noticed that I changed the naming convention a little bit:</p><ul><li>BloCSetting becomes StatesRebuilder</li><li>rebuildWidgets becomes rebuildStates.</li></ul><h4>How do I manage the state?</h4><p>As you can see, both <strong>scoped_model </strong>and BloC techniques end in calling setState() method somewhere in the code. scoped_model calls setState() inside an animatedWidget, and BloC inside StreamBuilder. I’m not an exception, I use the observer pattern and call <strong>setState()</strong>, in the <strong>update()</strong> method of the <strong>StateBuilder </strong>widget:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*p0v2A4TX272eSvET6QImOg.png" /></figure><p>and when you call <strong>rebuildStates </strong>method, you and calling the <strong>update() </strong>method of all registered <strong>StateBuilder </strong>widgets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*NtV4oUz6XbwhVF24ayc4UA.png" /></figure><h4>To the challenge:</h4><p>the MainBloc is as simple as in scoped_model MainModel. actually it looks similar to the scoped_model logic with one and important difference:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f0453fbf860d26e66ea3f674aeaa7746/href">https://medium.com/media/f0453fbf860d26e66ea3f674aeaa7746/href</a></iframe><p>I add a variable of type State named <strong>tappedCardTag</strong>. this variable is mutated in <strong>showDetailed </strong>method to hold the tag of the tapped card. When <strong>increment </strong>method is called the item of index equals <strong>detailedIndex </strong>is incremented and <strong>ONLY DETAILED CONTAINER (detailedWidgetState) AND THE TAPPED CARD (tappedCardTag) ARE REBUILT</strong>.</p><p>NB: I provided the BloC globally for simplicity.</p><p>the UI part of the challenge:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7d2cdac1b9bb812c449464acd5213f45/href">https://medium.com/media/7d2cdac1b9bb812c449464acd5213f45/href</a></iframe><p>lines 09–36 : <strong>StateBuilder </strong>is defined to make the horizontal ListView reactive. <br> — — — line 12: <strong>fetchItems(context)</strong> is called from the <strong>initState </strong>parameter, “context” here holds the tag of the widget to be used inside the <strong>mainBloc</strong>.<br> — — — line 13: check if items List is null, then show a circular progress indicator, if not null show the ListView;</p><p>lines 25–37 : <strong>StateBuilder </strong>is defined to make each individual <strong>itemCard </strong>reactive. It is defined using default tag because we will rebuild the widget from a function (<strong>showDetailed</strong>) called from the inside:<br> — — — line 31: the builder parameter is defined with “context” as function argument; the “context” is passed to<strong> showDetailed(randColor, index, context)</strong> to update the <strong>tappedCardTag </strong>to hold this tag of the tapped card in the bloc.</p><p>lines 42–54 : <strong>StateBuilder </strong>is defined to make each individual detailed container reactive. It is defined using user-defined tag because we will rebuild the widget from a function (<strong>showDetailed</strong>) called from the outside.</p><p>That is all, the simplest of the tree approach. Let’s see if it passes the challenge:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*S6FsaZ4olmgEzk0d2eCbAQ.gif" /></figure><p>Voila, the states_rebuilder wins the challenge.</p><p><strong>little bug:</strong></p><p>in the GIF below, if you tapped on the detailed container to increment the first <strong>itemCard</strong>, then if you scroll the ListView to the right until the first <strong>itemCard </strong>no longer visible. now if you scroll back to the first <strong>itemCard </strong>and top on the detailed container the <strong>itemCard </strong>does not update.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*1P-s7S88z9RMHEZ9hjbkpw.gif" /></figure><p>This behavior is expected because ListView.builder deposes <strong>itemCards </strong>that are not displayed and creates them if they are displayed again. In our case when we scroll back to display the first itemCard, a new BuildContext is created which is not the same as the BuildContext store in the <strong>tappedCardTag.</strong></p><p>To fix this bug we have to update the value of <strong>tappedCardTag </strong>to hold the newly create BuildContext of the <strong>itemCard</strong>. Here how to do it:</p><p>line 21–32 in UI code above are updated by adding the highlighted line:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*OeSLyXQz5X7hTgEsvwlS6w.png" /></figure><p>in the initState parameter, we call a new method from the mainBloc updateTappedState with state and index as parameter. in the bloc we add the updateTappedState method:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/1*3X3xGVwQAlifNizWwbDgrQ.png" /></figure><p>Each time an ItemCard is created, the <strong>updateTappedTag </strong>is called. we check if the index of the <strong>itemCard </strong>is equal to the <strong>detailedIndex </strong>and assign the passed state to the <strong>tappedCardTag</strong>. that all to do to fix the bug</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*-vHjWK_trfip_b-xJNb9Wg.gif" /></figure><p><strong>Animation with states_rebuilder</strong></p><p>states_rebuilder is so simple and powerful that we can separate animation setting from the UI. With states_rebuilder and only with it, animation setting is done inside the BloC and the UI is totally free of any animation mess.</p><p>look at this UI part:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dU_pdw7jspp_qUlevF91uA.png" /></figure><p>the other part of the code is the same as the basic example. As you can see there nothing related to animation in the UI except FractionalTranslation which is a simple widget from the basic flutter framework.</p><p>This is how increment() methods look like to animate the cards:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*e5ykwHiq1MVOQtX3hPk3UA.png" /></figure><p>here is the resulted animation from the above code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*CkmAdzzHwFI87G5mUJq3iQ.gif" /></figure><p>Actually when it comes to animation I have many challenges. With states_rebuilder I can control the animation of hundreds of tiny widgets. look at this LED sign:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*JwGEoAR1HGjA3XX1Jwyr7w.gif" /></figure><p>this is the UI part:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*oSU6hjDDKnUDiQXF4n3xaQ.png" /></figure><p>a simple GridView.count and a Container with an animated color value form the mainBloc.</p><p>super easy</p><h4>In conclusion:</h4><p>For small app, the states_rebuilder is the simplest with no side effects:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/326/1*x6F3zkH9R2mBxLdGVODBJA.png" /><figcaption>Schematic representation of one task app</figcaption></figure><p>When it comes to more complex app, the state management is still simple with full control on which widget to rebuild. The complexity lays in how much your logic is complex and on the number of pages you have but not on the state management.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/338/1*CcsB4fvEgZCTF8lML_b0uw.png" /><figcaption>Schematic representation of multi task app</figcaption></figure><p>states_rebuilder is the easiest, the most clean and the most powerful. With states_rebuilder you can achieve better-designed app and cleaned logic with little code.</p><p><strong>Now to the prize distribution ceremony :</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/1*pGK0f6GaM_fLDT3zQUNBAg.png" /><figcaption><a href="https://www.dreamstime.com/royalty-free-stock-photography-award-distribution-sport-competition-prize-ceremony-image32677707">https://www.dreamstime.com/royalty-free-stock-photography-award-distribution-sport-competition-prize-ceremony-image32677707</a></figcaption></figure><p>No matter which of the state management technique you use and support, let’s show our great fluttersmanship (sportsmanship) and applaud the winner with +50 claps 👏 👏.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*sZ2bOraVcDUfuS1EbiU6ZA.png" /><figcaption><a href="https://en.wikipedia.org/wiki/Sportsmanship#/media/File:USMC-110507-M-GR773-089.jpg">https://en.wikipedia.org/wiki/Sportsmanship#/media/File:USMC-110507-M-GR773-089.jpg</a></figcaption></figure><p>The link to the full code of this article will be available in comments sooner.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23ba11813a4f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/flutter-community/flutter-oneyearchallenge-scoped-model-vs-bloc-pattern-vs-states-rebuilder-23ba11813a4f">Flutter #OneYearChallenge; scoped_model vs BloC_pattern vs states_rebuilder</a> was originally published in <a href="https://medium.com/flutter-community">Flutter Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter and Web Code Sharing. A State Management demo]]></title>
            <link>https://medium.com/flutter-community/flutter-and-web-code-sharing-a-state-management-demo-2e615d3f2b1a?source=rss-818757b53c98------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e615d3f2b1a</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[MELLATI Fatah]]></dc:creator>
            <pubDate>Thu, 07 Feb 2019 00:04:37 GMT</pubDate>
            <atom:updated>2019-02-07T00:04:37.144Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*R6qf08qsAIJAb6MGOeLutQ.png" /></figure><h3>Introduction</h3><blockquote>Dart helps you craft beautiful, high-quality experiences across all screens</blockquote><p>This what you read on the home page of <a href="https://www.dartlang.org/">https://www.dartlang.org/</a> .</p><p>Next to it in the same page, the Dart team choose to impress new visitors by a demo example to compute π using the Monte Carlo method with pure Dart.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*niu-bMvwRwgFM9Gexu-xGg.png" /><figcaption>Dartlang home page</figcaption></figure><p>In this short article I try to impress you by the amount of logic code you can share between flutter and web and I will demonstrate to you how easy is state management in flutter. I will go through the steps to <strong>FLUTTERIZE </strong>this demo example highlighting the logic code sharing between these two platforms.</p><h3>Logic part (BloC):</h3><p>1- Create main_bloc.dart file and open an empty MainBloc class that extends the BloCSetting class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/1*tgMv8IO-PJEcx6Mc_bj1LQ.png" /><figcaption>main_bloc.dart</figcaption></figure><p>If you don’t understand what BlocSetting class is, do no worry I will explain it later in this article.</p><p>2- Just copy and past the code form the DartPad (<a href="https://dartpad.dartlang.org/fae22cffa7b184b4d27cd96dd633a5af">code here</a>) inside your MainBloc class. Obviously you have to put the Point class outside.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/1*qzus1PX1Rhqu1KcDv5sGOA.png" /><figcaption>main_bloc.dart.</figcaption></figure><p>As you can see the dart compiler underlines the errors. <strong><em>querySelector </em></strong>and <strong><em>window </em></strong>belong to the html package which we don’t need.</p><p>In the picture above I highlighted what I am going to modify to fix the errors.</p><p>3- What exactly the code does? I don’t know and I don’t care, all I know is that there are errors that I have to fix.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/525/1*FjUXAwDutW4O4sUDEHTgrQ.png" /><figcaption>main_bloc.dart. after error fixing.</figcaption></figure><ul><li>first I renamed the <em>main()</em> method. I chose to name it <em>init()</em> because I intend to call it form the <em>initState()</em> in the UI;</li><li>I replaced the “<em>var output = querySelector(#output)</em>” by a String variable “<em>ouput</em>” with an initial value of “?”;</li><li>for “<em>await window.animationFrame</em>”, I couldn’t come with a flutter exact equivalent. From rapid google research, suggestion are to use <em>scheduleFrameCallback </em>or <em>Ticker</em>. But any way, I chose to add a delay of 20 milliseconds which is equivalent to 50 Hertz (fps).</li></ul><p>That’s it, these are all the changes in the logic to make it compatible with flutter. As you can see we don’t even know about the UI part of our app.This is the real separation of concerns .</p><h3>Presentation part (UI):</h3><p>There is nothing special for the UI part. A Scaffold with MyHomePage() in the body property.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/1*690XZgJt2-fWY5o0ByZ_7A.png" /><figcaption>main.dart / MyHomePage class.</figcaption></figure><p>That’s it, supper easy.</p><p>If you are asking how to make this app reactive, this is a sign that you haven’t read my two articles about state managements yet.</p><h3>Adding reactivity:</h3><p>In the UI do the following changes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/1*FdObBM3ZTBx58QWiDjKkWg.png" /><figcaption>main.dart — changes are highlighted</figcaption></figure><p>wrap the widget you want to be reactive inside <em>stateBuilder</em>. In the <em>initState</em> property call the <em>init </em>method with “<em>state” </em>as parameter.</p><p>in the logic part do the following changes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*7nD7azhIc5Vkfn3CzR0law.png" /><figcaption>main_bloc.dart _ — changes are highlighted</figcaption></figure><p>now the app is reactive.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*QxDYk8VZi_Jw6eDRZw--4w.gif" /></figure><p>If you want to understand what happens please read my second article (<a href="https://medium.com/flutter-community/flutter-state-management-has-never-been-easier-think-statelessly-then-add-reactivity-d30c75760da0">here</a>), and If you want to know how does it work please read my first article (<a href="https://medium.com/flutter-community/flutter-state-management-setstate-fn-is-the-easiest-and-the-most-powerful-44703c97f035">here</a>).</p><h3>Conclusion</h3><p>From more than 30 lines of code, I changed only four and the result is as expected. This wouldn’t be possible with the other state management techniques. I hope I answered the question of those asking about asynchronous control of the UI. As I said in the comments of my previous article: I can use Futures without FutureBuilder and Streams without StreamBuilder.</p><p><a href="https://twitter.com/FlutterComm">JavaScript is not available.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e615d3f2b1a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/flutter-community/flutter-and-web-code-sharing-a-state-management-demo-2e615d3f2b1a">Flutter and Web Code Sharing. A State Management demo</a> was originally published in <a href="https://medium.com/flutter-community">Flutter Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>