<?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 Rafael Delos Santos on Medium]]></title>
        <description><![CDATA[Stories by Rafael Delos Santos on Medium]]></description>
        <link>https://medium.com/@themobilecoder?source=rss-65ffb0bde4c5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*UfyY1MDad0vecmC4jqGCkQ.png</url>
            <title>Stories by Rafael Delos Santos on Medium</title>
            <link>https://medium.com/@themobilecoder?source=rss-65ffb0bde4c5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 18:14:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@themobilecoder/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[Simpler and Better Flutter State Management with Cubit]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@themobilecoder/simpler-and-better-flutter-state-management-with-cubit-ff90d1cb6d08?source=rss-65ffb0bde4c5------2"><img src="https://cdn-images-1.medium.com/max/1700/0*WIV0scshWsleJjBe.png" width="1700"></a></p><p class="medium-feed-snippet">Learn how to use Cubit to cleanly organise our Flutter codebase to be more readable, scalable, and testable.</p><p class="medium-feed-link"><a href="https://medium.com/@themobilecoder/simpler-and-better-flutter-state-management-with-cubit-ff90d1cb6d08?source=rss-65ffb0bde4c5------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@themobilecoder/simpler-and-better-flutter-state-management-with-cubit-ff90d1cb6d08?source=rss-65ffb0bde4c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff90d1cb6d08</guid>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[flutter-widget]]></category>
            <category><![CDATA[flutter-state-management]]></category>
            <category><![CDATA[flutter-architecture]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Rafael Delos Santos]]></dc:creator>
            <pubDate>Tue, 23 Apr 2024 19:01:01 GMT</pubDate>
            <atom:updated>2024-04-24T10:02:10.067Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[How to use custom theme colours in Flutter without using Material or Cupertino Theme]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@themobilecoder/how-to-use-custom-theme-colours-in-flutter-without-using-material-or-cupertino-theme-295f3c5c0920?source=rss-65ffb0bde4c5------2"><img src="https://cdn-images-1.medium.com/max/1700/0*9ANzbmeK36DyryOE.jpg" width="1700"></a></p><p class="medium-feed-snippet">It is important to think about how to add structured colour theming to your design when building Flutter apps. The most popular way to do&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/@themobilecoder/how-to-use-custom-theme-colours-in-flutter-without-using-material-or-cupertino-theme-295f3c5c0920?source=rss-65ffb0bde4c5------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@themobilecoder/how-to-use-custom-theme-colours-in-flutter-without-using-material-or-cupertino-theme-295f3c5c0920?source=rss-65ffb0bde4c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/295f3c5c0920</guid>
            <category><![CDATA[flutter-color]]></category>
            <category><![CDATA[flutter-theme]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[flutter-design]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Rafael Delos Santos]]></dc:creator>
            <pubDate>Thu, 04 Apr 2024 20:01:23 GMT</pubDate>
            <atom:updated>2024-04-06T12:01:59.688Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[How to use PageView in Flutter]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@themobilecoder/how-to-use-pageview-in-flutter-cc2195949de1?source=rss-65ffb0bde4c5------2"><img src="https://cdn-images-1.medium.com/max/1684/1*h7NzSNKYFRnVwJ8LEIeJEQ.png" width="1684"></a></p><p class="medium-feed-snippet">Learn how to use PageView in Flutter to display sliding screens and pages.</p><p class="medium-feed-link"><a href="https://medium.com/@themobilecoder/how-to-use-pageview-in-flutter-cc2195949de1?source=rss-65ffb0bde4c5------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@themobilecoder/how-to-use-pageview-in-flutter-cc2195949de1?source=rss-65ffb0bde4c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc2195949de1</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[flutter-pagination]]></category>
            <category><![CDATA[flutter-widget]]></category>
            <category><![CDATA[flutter-layout]]></category>
            <dc:creator><![CDATA[Rafael Delos Santos]]></dc:creator>
            <pubDate>Fri, 29 Mar 2024 17:02:36 GMT</pubDate>
            <atom:updated>2024-03-29T17:02:36.977Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Flutter navigation with go_router package]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@themobilecoder/flutter-navigation-with-go-router-package-6060973bb8cb?source=rss-65ffb0bde4c5------2"><img src="https://cdn-images-1.medium.com/max/1920/0*SQ3CIBp2V_Z7414j.jpg" width="1920"></a></p><p class="medium-feed-snippet">Learn how to use the go_router navigation library in your Flutter app for moving from one screen to another.</p><p class="medium-feed-link"><a href="https://medium.com/@themobilecoder/flutter-navigation-with-go-router-package-6060973bb8cb?source=rss-65ffb0bde4c5------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@themobilecoder/flutter-navigation-with-go-router-package-6060973bb8cb?source=rss-65ffb0bde4c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/6060973bb8cb</guid>
            <category><![CDATA[flutter-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-navigation]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[flutter-application]]></category>
            <dc:creator><![CDATA[Rafael Delos Santos]]></dc:creator>
            <pubDate>Thu, 15 Feb 2024 09:01:37 GMT</pubDate>
            <atom:updated>2024-02-21T05:51:29.656Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Build a simple game with Flutter and Flame]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@themobilecoder/build-a-simple-game-with-flutter-and-flame-52ad7caf2701?source=rss-65ffb0bde4c5------2"><img src="https://cdn-images-1.medium.com/max/1920/0*RDIn7LsSZDBfvGJG.jpg" width="1920"></a></p><p class="medium-feed-snippet">Learn how to build a simple game in Flutter by using the Flame package.</p><p class="medium-feed-link"><a href="https://medium.com/@themobilecoder/build-a-simple-game-with-flutter-and-flame-52ad7caf2701?source=rss-65ffb0bde4c5------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@themobilecoder/build-a-simple-game-with-flutter-and-flame-52ad7caf2701?source=rss-65ffb0bde4c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/52ad7caf2701</guid>
            <category><![CDATA[flutter-game]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutterflame]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <dc:creator><![CDATA[Rafael Delos Santos]]></dc:creator>
            <pubDate>Tue, 06 Feb 2024 09:00:53 GMT</pubDate>
            <atom:updated>2024-02-08T04:37:08.964Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[How to use Isolates for parallel processing in Flutter]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@themobilecoder/how-to-use-isolates-for-parallel-processing-in-flutter-6bb8a68b9eed?source=rss-65ffb0bde4c5------2"><img src="https://cdn-images-1.medium.com/max/1700/0*OSHUnIwGExhIFHFF.jpg" width="1700"></a></p><p class="medium-feed-snippet">Learn the basics of running tasks in parallel in Flutter using Isolate.</p><p class="medium-feed-link"><a href="https://medium.com/@themobilecoder/how-to-use-isolates-for-parallel-processing-in-flutter-6bb8a68b9eed?source=rss-65ffb0bde4c5------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@themobilecoder/how-to-use-isolates-for-parallel-processing-in-flutter-6bb8a68b9eed?source=rss-65ffb0bde4c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/6bb8a68b9eed</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-threads]]></category>
            <category><![CDATA[flutter-concurrency]]></category>
            <category><![CDATA[flutter-background]]></category>
            <category><![CDATA[flutter-isolate]]></category>
            <dc:creator><![CDATA[Rafael Delos Santos]]></dc:creator>
            <pubDate>Tue, 07 Nov 2023 09:00:32 GMT</pubDate>
            <atom:updated>2023-11-12T09:02:59.385Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[On the importance of abstraction when using third-party libraries]]></title>
            <link>https://medium.com/@themobilecoder/on-the-importance-of-abstraction-when-using-third-party-libraries-baa5d5bd8c24?source=rss-65ffb0bde4c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/baa5d5bd8c24</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[wrapper-class]]></category>
            <category><![CDATA[abstraction]]></category>
            <category><![CDATA[solid-principles]]></category>
            <category><![CDATA[best-practices]]></category>
            <dc:creator><![CDATA[Rafael Delos Santos]]></dc:creator>
            <pubDate>Fri, 29 Sep 2023 10:01:03 GMT</pubDate>
            <atom:updated>2023-10-02T07:01:35.644Z</atom:updated>
            <content:encoded><![CDATA[<p>Learn the importance of abstraction when calling third-party libraries to keep your code testable, scalable, and resilient to future changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RLRk5ORn1AA57HXu.jpg" /></figure><p>A good rule of thumb when using a third-party library is to use wrapper functions to abstract the implementation instead of calling their APIs directly. Doing so makes your code easily testable and flexible whenever you decide to use a different library.</p><p>This applies to third-party libraries that use databases, networking, hardware sensor events, and more.</p><p>I will share some insights on how abstraction allows us to move faster in developing new features while keeping our code testable. Imagine we are tasked to make a feature-rich Android app for taking card payments. This app will depend on a particular vendor that builds the device and provides us with an SDK (Software Development Kit) along with it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*kI-kowqj0s2tUq-FRGvAJQ.png" /><figcaption>Initial payment app architecture</figcaption></figure><h3>Directly using a third-party library influences the app’s architecture</h3><p>The quickest way to use a library is by calling its APIs directly. When building an app, it is straightforward to adapt to what the SDK interface gives you.</p><p>Suppose the VendorSdk has an API for payment like this.</p><pre>interface VendorSdk {<br><br>    enum class VendorPaymentStatus {<br>        SUCCESS,<br>        FAILED,<br>        CARD_DENIED<br>    }<br><br>    fun makePayment(amount: Int, resultCallback: (VendorPaymentStatus) -&gt; Unit)<br><br>}</pre><p>In this example, the vendor SDK provides a makePayment function that accepts an amount and informs the caller of the payment result through the resultCallback function argument.</p><p>If I implement a payment flow within FeatureA, it would look something like this.</p><pre>class FeatureA constructor(<br>    private val vendorSdk: VendorSdk,<br>    private val analyticsService: AnalyticsService<br>) {<br>    fun triggerCardPayment(amount: Int, paymentResultCallback: (isSuccessful: Boolean) -&gt; Unit) {<br>        vendorSdk.makePayment(amount) { vendorPaymentStatus: VendorSdk.VendorPaymentStatus -&gt;<br>            when (vendorPaymentStatus) {<br>                VendorSdk.VendorPaymentStatus.SUCCESS -&gt; {<br>                    analyticsService.reportSuccessfulPayments()<br>                    paymentResultCallback(true)<br>                }<br>                else -&gt; {<br>                    analyticsService.reportUnsuccessfulPayments()<br>                    paymentResultCallback(false)<br>                }<br>            }<br>        }<br>    }<br>}</pre><p>This implementation looks fine. The FeatureA module has access to VendorSdk, which in turn has access to the device&#39;s hardware for making payments. But notice how FeatureA has to adapt VendorSdk&#39;s interface which in this case is a callback function.</p><p>There is nothing wrong with defining the triggerCardPayment() method in FeatureA to accept a callback function. The problem is that we were somehow forced to include paymentListener because the SDK requires one. That is the only way we can handle the payment result of the VendorSdk.</p><p>This might pose a problem because our entire app depends on how to use a specific vendor SDK and how it defines a particular way of getting the result. What if we decide to move to another vendor? Changing all the feature blocks to adhere to a new interface is very time-consuming. The ideal approach when migrating to another vendor’s SDK is only to change a single point in our app.</p><h3>Create a wrapper class to abstract a third-party library’s API</h3><p>A wrapper class (or function) in programming is a container whose purpose is to call another function. It might seem redundant, but this approach introduces a few advantages to improve our code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/0*JqgbSOCscl_MkEDH.png" /><figcaption>App architecture with PaymentWrapper included</figcaption></figure><p>With this approach, we can decide how we pass and receive data between the app and the VendorSDK. This extra layer will transform data and define the interface the app expects from third-party libraries.</p><p>In rare instances when a particular third-party library has been deprecated, moving to another library will only involve changing the Wrapper container whilst keeping the features of our app the same. This is in line with the principle of <em>coding against interfaces, not implementations</em> where the PaymentWrapper is such an interface to one or more different third-party libraries.</p><p>Returning to our example, we might implement a PaymentWrapper that looks like this.</p><pre>interface PaymentWrapper {<br>    suspend fun pay(amount: Int) : PaymentResult<br><br>    enum class PaymentResult {<br>        SUCCESS,<br>        FAILED<br>    }<br>}<br><br>class VendorSdkPaymentWrapper constructor(<br>    private val vendorSdk: VendorSdk,<br>) : PaymentWrapper {<br>    override suspend fun pay(amount: Int): PaymentWrapper.PaymentResult {<br>        try {<br>            val completableDeferred = CompletableDeferred&lt;PaymentWrapper.PaymentResult&gt;()<br>            return withTimeout(5_000) {<br>                vendorSdk.makePayment(amount) { result -&gt;<br>                    when (result) {<br>                        VendorSdk.VendorPaymentStatus.SUCCESS -&gt; {<br>                            completableDeferred.complete(PaymentWrapper.PaymentResult.SUCCESS)<br>                        }<br>                        else -&gt; {<br>                            completableDeferred.complete(PaymentWrapper.PaymentResult.FAILED)<br>                        }<br>                    }<br>                }<br>                completableDeferred.await()<br>            }<br>        } catch (e: Exception) {<br>            return PaymentWrapper.PaymentResult.FAILED<br>        }<br>    }<br>}</pre><p>As a team decision, we may have agreed to have our payment interface return the payment result from the function call instead of through a callback function. We can transform this approach in the VendorSdkPaymentWrapper.</p><p>The FeatureA module can adapt to this interface without knowing how the vendor implements their payment flow. We could potentially write the FeatureA as follows where the triggerCardPayment() can be run on a separate coroutine (asynchronously):</p><pre>class FeatureA constructor(<br>    private val paymentWrapper: PaymentWrapper,<br>    private val analyticsService: AnalyticsService,<br>    private val coroutineContext: CoroutineContext<br>) {<br>    suspend fun triggerCardPayment(amount: Int) : Boolean {<br>        val result = paymentWrapper.pay(amount)<br>        return when(result) {<br>            PaymentWrapper.PaymentResult.SUCCESS -&gt; {<br>                analyticsService.reportSuccessfulPayment()<br>                true<br>            }<br>            else -&gt; {<br>                analyticsService.reportUnsuccessfulPayment()<br>                false<br>            }<br>        }<br>    }<br>}</pre><p>In this particular example, this is a better approach than using a callback function because there is a chance that the callback function may never be called, rendering your app to be stuck if there are no safeguards for timeouts.</p><p>The important thing here is that the PaymentWrapper interface is dependent on your (or your team&#39;s) decision and not decided by the third-party library that you&#39;re using.</p><p>Now that there’s an abstraction on how we make payments, our code will be easier to change if the vendor SDK changes its implementation.</p><h3>Running automated tests with third-party libraries</h3><p>For the most part, running automated tests on an app that includes third-party libraries on emulators or simulators works fine as long as these libraries depend on common platform APIs such as Android or iOS frameworks. But what happens if a library is hardware-dependent?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DEY31YiB5_zpUMMD.png" /><figcaption>Running UI tests on an emulator breaks when a third-party library depends on specific hardware</figcaption></figure><p>If we want to run automation tests on an emulated device when a particular SDK only works on real devices, then using the third-party library directly will not work. In our payment app, these automation tests would fail as emulators do not have the necessary hardware for payment.</p><p>The good thing is that with the PaymentWrapper we wrote, it is easier to make testing possible by changing a few bits in our implementation.</p><h3>Use interfaces or abstract classes when writing wrapper classes</h3><p>Use the abstract or interface construct when writing your wrapper functions or classes (as long as your framework supports it). This approach makes it easier to swap implementation whenever needed. Since we have already written PaymentWrapper as an interface, we can simply write up new implementations according to the services we need.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/0*6cG2610Efe5avYg5.png" /><figcaption>Different implementation of PaymentWrapper through extension</figcaption></figure><p>Our app will have two instances of PaymentWrappers, one for running the real app for production and the other for running UI tests on emulators.</p><pre>class UiTestPaymentWrapper : PaymentWrapper {<br>    override suspend fun pay(amount: Int): PaymentWrapper.PaymentResult {<br>        return PaymentWrapper.PaymentResult.SUCCESS<br>    }<br>}</pre><p>The implementation of UiTestPaymentWrapper does not depend on the VendorSdk, so we are sure that this will run on UI tests. In this example, calling the pay() method always returns a successful result. To change this result, you can introduce a setter() function and change the return value according to different test cases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EtyLgHo8L2y79L64.png" /><figcaption>Inject the correct instance of PaymentWrapper according to use-case</figcaption></figure><p>Swapping implementations of PaymentWrapper when building the app depends on how you implement dependency management, and how these dependencies are injected into your wrappers. (For Android, Hilt is a popular dependency injection library).</p><p>As mentioned before, this approach also solves the problem of migrating from one vendor to another. Instead of rewriting everything, we only need to add another implementation of PaymentWrapperthat adheres to the interface of the new vendor SDK. Each feature&#39;s existing implementation and tests will be untouched because the interface never changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Om-J9Irntdw8nhqN.png" /><figcaption>Migrate to a new library by creating a new instance of PaymentWrapper while the rest of the app remains unchanged.</figcaption></figure><h3>Conclusion</h3><p>Abstraction of third-party libraries can make your app more scalable, testable, and flexible when it comes to changes. Using wrapper classes as an abstraction can keep your features unchanged regardless of how a third-party library is implemented under the hood. This extra layer may seem like additional work, but the benefits of being resilient to dependency changes and testable code far outweigh the time cost.</p><p><em>Originally published at </em><a href="https://themobilecoder.com/on-the-importance-of-abstraction-when-using-third-party-libraries/"><em>https://themobilecoder.com</em></a><em> on September 29, 2023.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=baa5d5bd8c24" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Future in Flutter — Get comfortable with asynchronous data]]></title>
            <link>https://medium.com/@themobilecoder/using-future-in-flutter-get-comfortable-with-asynchronous-data-841aba06c81e?source=rss-65ffb0bde4c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/841aba06c81e</guid>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[flutter-tutorial]]></category>
            <category><![CDATA[flutter-future]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-beginner]]></category>
            <dc:creator><![CDATA[Rafael Delos Santos]]></dc:creator>
            <pubDate>Tue, 19 Sep 2023 08:00:53 GMT</pubDate>
            <atom:updated>2023-09-20T11:04:44.965Z</atom:updated>
            <content:encoded><![CDATA[<h3>Using Future in Flutter — Get comfortable with asynchronous data</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WiJ5FvP93QXBv7Yc.jpg" /><figcaption>Photo by <a href="https://unsplash.com/@karim_manjra?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Karim MANJRA</a> on <a href="https://unsplash.com/photos/dtSCKE9-8cI?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>A Future refers to an object that can hold data at a point in time when it is ready to do so. This is used in cases where the app should not block or freeze other processes if the data needed has not been obtained yet.</p><p>Learning to use Future in Flutter is essential because many applications you build will rely on packages and APIs that use Futures extensively. It also makes your app responsive. An app without Futures is like an app without features ( <em>get it?</em> 😇).</p><h3>Why do we need to use Future in Flutter?</h3><p>It is easier to understand the concept of Future with examples. Let&#39;s look at a simple example: <strong>fetching data from the internet</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*o3Lu9wfwueOfM7YY.png" /><figcaption>Downloading an image through a slow network</figcaption></figure><p>For simplicity’s sake, let’s write up a simple function that gets data from the internet and returns this value as a String. Because we are not using a Future, the code will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dUb6PbOKlYjv44nK.png" /><figcaption>Blocking operation to download from the internet</figcaption></figure><p>This code is a straightforward approach to fetching data from a website, but what happens then if the internet connection of the device is slow?</p><p>The line of code that gets the data will operate for a few seconds before it returns the result. This will cause the app to block until the work is complete.</p><p>You will not have a chance to show a loading animation or do anything else because this line of code is blocking or synchronous, rendering your app unresponsive.</p><h3>Use Future for operations that take time to complete</h3><p>If a function takes a long time to complete, then it is preferred to use Futures.</p><p>A Future can execute operations without blocking. Once the data is ready, a callback will be executed with the data ready to be used.</p><p>Let’s use the http library as an example to get data from the internet. The http package has an API to make a GET request, which returns a Future of data type Response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7d4-5PHK2ln1v2n-.png" /><figcaption>Using <strong>http</strong> package to fetch data</figcaption></figure><p>Since the object that we get from the http.get() method is a Future, the futureResponse value does not necessarily contain the actual response of fetching the data from some website.</p><p>The good news is this call to fetch the data will not block your app. But how can we obtain and use the actual value of the futureResponse?</p><h3>Getting the value from Future asynchronously using callbacks</h3><p>One way of evaluating the Future is to use callbacks.</p><p>For successful evaluation, we can use the Future function .then() which accepts a callback function to consume the Future value.</p><p>In some cases, evaluating a Future may throw an error or an exception. We can use the .onError() function to add a callback for this situation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*18lU-faF-VLS7dk2.png" /><figcaption>Use <strong>.then()</strong> and <strong>.error()</strong> to handle <strong>Future</strong> values with callback functions</figcaption></figure><p>Most use cases of using callbacks on Future values involved terminal operations such as saving to databases, sending analytics events, and other processes that do not require their results to be returned by the function.</p><h3>Getting the value from Future synchronously using async and await</h3><p>There are instances when we want to use the value of a Future such as transforming this into another object. In cases like this, the callback approach will not work because callback values cannot be returned by the function.</p><p>To evaluate the value of the Future, we need to use the keywords async and await.</p><h4>The async keyword</h4><p>The async keyword modifies a function so that we can evaluate a Future value in that function using the await keyword. Keep in mind that marking your function as async means that it can never return data types other than void and Future&lt;T&gt; and will result in a compilation error if you try.</p><p>To define a function to be asynchronous, add the async keyword after the function name signature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NXvS5KC7d2rE_l6a.png" /><figcaption>The correct and incorrect ways of using <strong>async</strong> keyword</figcaption></figure><h4>The await keyword</h4><p>The key to evaluating a Future synchronously is by using the await keyword. When you add an await keyword before a Future value or a function that returns a Future, this line will block and <strong>wait</strong> until the value has been evaluated.</p><p>The await operation will only work if this code is in an async function and will throw a compilation error if it is missing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tVBBcTl1-lBirtFP.png" /><figcaption>The <strong>await</strong> keyword waits for the value of a <strong>Future</strong></figcaption></figure><p>In the example above, we have the getAlbumFromInternet() function that represents fetching data from the internet. Since this function is an async function, we can use the await keyword to evaluate the value of a Future.</p><p>Evaluating the Future.delayed() with async keyword will block this line until the elapsed duration. We also use the constructor Future.value() to return a Future with the value &#39;Album name&#39;.</p><p>Using the same example, we have an asynchronous function that can evaluate another function that returns a Future. Inside the getAlbumName(), we can synchronously wait for the value of getAlbumName() with the await keyword.</p><p>In short, use await to evaluate the value of a Future inside an async function.</p><h3>Using Future in Flutter widgets</h3><p>Now that we have covered the basics of Future and the necessary keywords to use them, we can move on to using these concepts in a Flutter app.</p><h4>FutureBuilder&lt;T&gt; widget</h4><p>The most basic way of consuming Future objects in a widget is through the FutureBuilder&lt;T&gt;.</p><p>Building this widget requires a few parameters.</p><p>The first parameter is the Future itself future: which will be evaluated when the widget is built. This argument allows you to set the Future that you want to get a value from.</p><p>The next one is the initial value initialData: of type T which will be used when the Future&lt;T&gt; value has not been evaluated yet. This is useful for situations where the Future takes time to assess, such as fetching data with slow internet or doing long processes in the background. Although not a required argument, it&#39;s better to include an initial value to constrain the possible values of the Future.</p><p>Finally, the most important argument of a FutureBuilder is the builder: itself. The builder function lets you decide what widget to display depending on the state of the future based on its function argument AsyncSnapshot&lt;T&gt;.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sH79Dd3A98Im_53a.png" /><figcaption>Example use of <strong>FutureBuilder</strong></figcaption></figure><p>The builder function of the FutureBuilder&lt;T&gt; provides access to an AsyncSnapshot argument that gives you both the current state and the current value of the Future that you provided.</p><p>You can get the current state of the FutureBuilder through the snapshot.connectionState getter method. The values include active, waiting, done, or none. In most cases, you can check the connectionState if it is done and then show the appropriate widget by obtaining the value of the Future using snapshot.data.</p><p>The current value of the Future can be null sometimes depending on the state of Future, that&#39;s why it is better to do a null check on snapshot.data or validate the current state through snapshot.connectionState to show the appropriate widget.</p><h3>Sample weather app using Future</h3><p>Let’s put our learnings into practice by creating a simple app that fetches data from a publicly available API.</p><h4>Setup</h4><p>A weather app can be a good example to demonstrate the use of Futures.<br>One of my favourite sources of free public APIs is the <a href="https://github.com/public-apis/public-apis?ref=themobilecoder.com">public-api repo</a> from Github, so let&#39;s use one of the weather API there called open-meteo.</p><p>In this example, we will need to use the http package for fetching data from the internet. The result is a json formatted file, so we will also need the dart:convert for converting json formatted string to a usable object in our app.</p><p>Install the http package by running flutter pub add http on the terminal inside your project directory, or add http: ^1.1.0 ( <em>latest version at the time of writing</em>) as part of your dependencies inside the pubspec.yaml.</p><p>As I am using a macOS machine to run this app, I also have to add the necessary permission to access the network by adding this snippet in macos/Runner/DebugProfile.entitlements.</p><pre>&lt;key&gt;com.apple.security.network.client&lt;/key&gt; <br>&lt;true/&gt;</pre><blockquote>Accessing data from the internet requires network permission on your device. Head over to <a href="https://docs.flutter.dev/data-and-backend/networking">https://docs.flutter.dev/data-and-backend/networking</a> to learn how to add network permission on the device you’re using to run this example app.</blockquote><h3>App source code</h3><p>Here’s the full code for our weather app example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*l-3UmpwvjKIdWMAT.png" /><figcaption>Sample Weather app that uses Future to obtain and display the current temperature</figcaption></figure><p>When you run this code, you should have something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/0*JksT-D2czBK6fiJz.gif" /><figcaption>Weather app running on desktop</figcaption></figure><h3>Code explanation</h3><p>Let’s dissect the source code and understand what each of the parts is doing by first looking at the getCurrentWeather() Future function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*z6PpnngPAf5bc8YO.png" /><figcaption>The <strong>async</strong> function <strong>getCurrentWeather()</strong></figcaption></figure><p>The getCurrentWeather() function provides our app with the weather data that we need to display. Since we know that fetching data from the internet may block our app while waiting for the result, this is the perfect time to use a Future&lt;T&gt;.</p><p>We also want to display the weather data as a String, so we defined the return type to be Future&lt;String&gt;.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oDRgsgwFhsY49caw.png" /><figcaption>Blocking operation to obtain the response using <strong>await</strong></figcaption></figure><p>The first thing that this function does is to fetch data from the open-meteo API. Since we need to process the JSON result from http.get(), we have to use the await keyword to block this function while waiting for the result.</p><p>The response will have a data type Response as part of the http interface. The response body will have a value in JSON format similar to this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Jxwc8ymtppMsGKkN.png" /><figcaption>Weather data in JSON format</figcaption></figure><p>We use the jsonDecode from dart:convert package to convert this JSON object into a Map. Since we want to traverse this JSON and get the current_weather, we access this value using the Map interface.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xwC9DUukuajCBtYl.png" /><figcaption>Converting JSON data to map</figcaption></figure><p>Once we have the temperature value, we can return this value to type Future&lt;String&gt; by constructing a Future with the temperature as its value in String.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RROkoJUDOd6DkJtv.png" /><figcaption>Constructor method of a <strong>Future</strong> with value</figcaption></figure><h3>Data fetch is asynchronous</h3><p>While all the data were being fetched and converted from the internet, the sample app <strong>DOES NOT</strong> block because we use a FutureBuilder that processes the Future. If we look at the FutureBuilder, we show a Loading widget while waiting for the Future to get the actual result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1cLsKJPlrPRQpvsa.png" /><figcaption>Implementation example of using <strong>FutureBuilder</strong></figcaption></figure><p>This is one way of ensuring we display the appropriate widget according to the state of the Future. We can check for the current status of the Future in a FutureBuilder by using the ConnectionState of the snapshot argument in the function. Based on the status, we can decide which widget to display, such as a loading spinner widget or an error widget, whichever is more appropriate.</p><p>The sample app shows a Text widget with a Loading text because the snapshot.connectionState is equal to active as it has not finished fetching the data yet.</p><p>The snapshot argument also lets you know if an error has occurred so you can display the appropriate message to the app&#39;s users.</p><h3>Conclusion</h3><p>Implementing Futures is an essential part of responsive apps in Flutter. Using Future allows your app to process data asynchronously so it can run smoothly.</p><p>Understanding Futures also lets you use a wide range of Flutter packages, which is very important to save time creating your own features.</p><h3>Reference</h3><p><a href="https://api.flutter.dev/flutter/dart-async/Future-class.html">https://api.flutter.dev/flutter/dart-async/Future-class.html</a></p><p><em>Originally published at </em><a href="https://themobilecoder.com/using-future-in-flutter/"><em>https://themobilecoder.com</em></a><em> on September 19, 2023.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=841aba06c81e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dependency Injection in Flutter using Riverpod]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@themobilecoder/dependency-injection-in-flutter-using-riverpod-a48d6adde2a?source=rss-65ffb0bde4c5------2"><img src="https://cdn-images-1.medium.com/max/1700/0*bO_h0zi3jOQbkBRR.jpg" width="1700"></a></p><p class="medium-feed-snippet">Learn a simple method to apply dependency injection in Flutter using the popular state management framework Riverpod.</p><p class="medium-feed-link"><a href="https://medium.com/@themobilecoder/dependency-injection-in-flutter-using-riverpod-a48d6adde2a?source=rss-65ffb0bde4c5------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@themobilecoder/dependency-injection-in-flutter-using-riverpod-a48d6adde2a?source=rss-65ffb0bde4c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/a48d6adde2a</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[riverpod]]></category>
            <category><![CDATA[flutter-architecture]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <dc:creator><![CDATA[Rafael Delos Santos]]></dc:creator>
            <pubDate>Tue, 08 Aug 2023 10:00:57 GMT</pubDate>
            <atom:updated>2023-08-17T04:10:29.603Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Flutter setState — The simplest state management in Flutter]]></title>
            <link>https://medium.com/@themobilecoder/flutter-setstate-the-simplest-state-management-in-flutter-ae9838b94720?source=rss-65ffb0bde4c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae9838b94720</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-state-management]]></category>
            <category><![CDATA[flutter-beginner]]></category>
            <dc:creator><![CDATA[Rafael Delos Santos]]></dc:creator>
            <pubDate>Tue, 25 Jul 2023 10:01:12 GMT</pubDate>
            <atom:updated>2023-07-26T10:02:21.400Z</atom:updated>
            <content:encoded><![CDATA[<h3>Flutter setState — The simplest state management in Flutter</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RO8f_CeO-sgEh0dn.jpg" /><figcaption>Photo by <a href="https://unsplash.com/ko/@snowshade?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Oleg Laptev</a> on <a href="https://unsplash.com/photos/QRKJwE6yfJo?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>We will discuss setState(); the easiest and simplest state management approach in Flutter. Many great state management libraries are available in Flutter, but it is important to know the most basic approach to update the UI state of your app.</p><p>You might be tempted to jump to learning BLoC, Provider, Riverpod, and the thousands of other frameworks available, but learning the fundamentals is more important than complex solutions. Once you understand the basics, you might even decide to make your own state management framework.</p><h3>What is the setState method?</h3><p>Stateful widgets have this method called setState() which tells the Flutter framework that this StatefulWidget&#39;s state has been updated and needs to be replaced.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N-qg9OJmIZRsi90JWcBdig.png" /><figcaption>setState syntax</figcaption></figure><p>When setState() method is called, the State of the StatefulWidget gets replaced with a new one, where the updates inside declared inside the setState() function will be applied.</p><h3>How do you use setState?</h3><p>It is good practice to call setState() from one-time events such as button presses or other user-input triggers.</p><p>To make setState work as intended, you have to update a state in your app inside the callback argument of this method. For example, if we want to increase the counter when pressing a button and want to display this updated value on the screen, we can write the code as such:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fxU8niIdu964CFsj8n-Zow.png" /><figcaption>Using setState inside onTap callback</figcaption></figure><p>In the sample code, the state that we want to update is the _counter member variable. Every time we tap the button, the counter is updated by one. Subsequently, the widget is redrawn from the screen and uses this updated value.</p><p>The setState() method should not be called in the State&#39;s build() function. The reason is that every time you call setState() and there is a new state, the build function will be called recursively.</p><blockquote>setState() should not be called in the build() function and should only be triggered from user events such as button clicks.</blockquote><h3>Simple Example — Changing the theme colour</h3><p>Let’s put our setState() knowledge into practice by building a simple desktop app that changes its theme when pressing a button. In this example, we will put the whole app in one file to see how setState() works the best.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hzwr2I0uetC_ndWWtWfV8A.png" /><figcaption>SimpleThemeColorApp behaviour when triggering setState() method</figcaption></figure><p>Remember that setState() only works on StatefulWidget so for this simple example, we will build our app as a StatefulWidget.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SE3u5L1Zbxuvu9k3igpccw.png" /><figcaption>simple_theme_color_app.dart</figcaption></figure><p>We built the SimpleThemeColorApp widget which extends a StatefulWidget to add an option to save state. The state of this app is the _materialColor which defaults to blue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*VBlhgDR38NlPMih23TfBow.gif" /><figcaption>Demo app using setState to update the theme</figcaption></figure><p>In order to update the theme, we need to add an onTap listener in the buttons that call the setState() method. Do not forget to add the callback that sets the new value of the _materialColor.</p><h3>Updating the state without setState</h3><p>You might think that you can just set the _materialColor property without setState(). If you do this, the _materialColor property will be updated; the screen however will not.</p><p>The reason behind this behaviour comes from the idea that widgets are immutable. Widgets cannot change once rendered BUT they can be replaced.</p><p>Changing the StatefulWidget&#39;s state through setState() triggers the rebuilding of this widget. Once this widget has been rebuilt, you can see the updated display.</p><h3>Complex example — Changing the theme colour outside the StatefulWidget</h3><p>It gets a bit trickier when you want to update the state of a widget from another widget. Let’s look at an example where the Theme of the app is declared at the topmost parent widget of the tree.</p><p>If we have independent and separate widgets for different screens in the app, they would not have access to the state of the topmost parent widget. So how do we update the state from these widgets?</p><p>We can pass <strong>callbacks</strong> as part of the widget’s constructor parameters. These callbacks can be defined when the parent widget creates these child widgets and pass the setState() function altogether.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mEcJCP8TJp06FTBTt75LLA.png" /><figcaption>complex_theme_color_app.dart</figcaption></figure><p>In the code example, our topmost parent widget is the ComplexThemeColorApp. The state member of this widget <em>(</em><em>_ComplexThemeColorAppState)</em> keeps the theme colour variable _materialColor which is used to set the theme colour of the app.</p><p>The child widget PageWidget will be the screen that contains the buttons to change the theme. Note that when constructing this widget, it requires a function parameter called updateThemeCallback to update the state. This function accepts a MaterialColor as a parameter.</p><p>Let’s define the PageWidget as a row containing two buttons; one for each colour. Since this widget has the callback, we can set this as the function to be called when we tap each of the buttons, each with its corresponding colour.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*obxrQ6HPV9Uz2dq4hBz3hQ.png" /><figcaption>page_widget.dart</figcaption></figure><p>The resulting app will be the same as the one shown in the basic example and only the code implementation is different.</p><h3>Limitations</h3><p>You will notice that this approach is not scalable. It works on widget trees that are one, or even two levels deep, but not more than that. Adding callbacks can be a nightmare especially when you start building complex widget trees.</p><p>The ideal approach to solve this problem is for a widget to be able to access a state within its scope, update it, and the widgets listening to the state will be reconstructed and updated.</p><h3>Enter the state management frameworks</h3><p>The setState() method is best used for updating the state of a single StatefulWidget. It&#39;s time to use an appropriate state management framework when your app starts to become more complex.</p><p>The Flutter development team has suggested a number of frameworks to use to handle states. I have mentioned these libraries in the introduction <em>(BLoC, Provider, Riverpod, etc)</em> and are all well-suited for handling states in Flutter.</p><p>We will discuss these better state management frameworks in another article.</p><h3>Summary</h3><p>Widgets are immutable by nature therefore we need to rebuild the widgets if we want to display a new state. The simplest way to update the state of a StatefulWidget is by using setState(). To use setState(), update the member variable of your widget in the callback function of setState(). This will rebuild the widget with the new value which then updates the display of your app.</p><h3>References</h3><ul><li><a href="https://api.flutter.dev/flutter/widgets/State/setState.html?ref=themobilecoder.com">https://api.flutter.dev/flutter/widgets/State/setState.html</a></li></ul><p><em>Originally published at </em><a href="https://themobilecoder.com/flutter-setstate-the-simplest-state-management-in-flutter/"><em>https://themobilecoder.com</em></a><em> on July 25, 2023.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae9838b94720" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>