<?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 Aditya Rohman on Medium]]></title>
        <description><![CDATA[Stories by Aditya Rohman on Medium]]></description>
        <link>https://medium.com/@aditya-rohman?source=rss-8f67b6db7256------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*y1I0heivPIwVJte6GW-MVw.png</url>
            <title>Stories by Aditya Rohman on Medium</title>
            <link>https://medium.com/@aditya-rohman?source=rss-8f67b6db7256------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 19:57:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aditya-rohman/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[How to Design an Effective Bloc State Management in Flutter Development]]></title>
            <link>https://levelup.gitconnected.com/how-to-design-an-effective-bloc-state-management-in-flutter-development-972baa620dc4?source=rss-8f67b6db7256------2</link>
            <guid isPermaLink="false">https://medium.com/p/972baa620dc4</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[flutter-state-management]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Aditya Rohman]]></dc:creator>
            <pubDate>Tue, 25 Jul 2023 19:15:54 GMT</pubDate>
            <atom:updated>2023-07-26T03:08:44.477Z</atom:updated>
            <content:encoded><![CDATA[<h4>The comparison between different approaches in designing the bloc state management for flutter app development and speeding up bloc creation by utilizing the <em>freezed</em> package.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tMM2TDewTghjBr2YnReUaA.png" /></figure><p>Flutter is closely related to <strong>state management</strong>. Many types and approaches of state management can be used out there. In this article, I will talk about the <strong>bloc state management</strong>.</p><p>As an introduction, a bloc <strong>consists of three main parts</strong> to manage the state of an application built with Flutter. There are State, Event, and Bloc itself. I’m going to talk about the State part specifically. There are two common ways to create or design the State of a bloc. Also, I’ll provide some tips on how to create a bloc effectively in terms of time that will speed up the development process.</p><h3>Single-State Design</h3><p>The first approach is by creating a single state class that <strong>holds all data or payload</strong> to be shared with the pages or widgets later. Here’s an example of what this approach looks like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/05688ea680e0bcf1c4dd558783fed3e9/href">https://medium.com/media/05688ea680e0bcf1c4dd558783fed3e9/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e2e2b2ce249f5f893a4a260760289f4/href">https://medium.com/media/8e2e2b2ce249f5f893a4a260760289f4/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6621211435824dccbc9e8e2fa895ee02/href">https://medium.com/media/6621211435824dccbc9e8e2fa895ee02/href</a></iframe><h4>Optimization</h4><p>The above code can be simplified using freezed package that is responsible for generating the boilerplate like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/577e81137347a38689f92846eed84d2b/href">https://medium.com/media/577e81137347a38689f92846eed84d2b/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cce55f05f0c47ee61518c57c6d57e374/href">https://medium.com/media/cce55f05f0c47ee61518c57c6d57e374/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/415397ee1608f2845b200120f4e50153/href">https://medium.com/media/415397ee1608f2845b200120f4e50153/href</a></iframe><h4>Pros</h4><ul><li>It’s easier to access <strong>data or payload</strong> inside the state from either BlocConsumer, BlocListener, or BlocBuilder like so:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7841efe152fe89570f1a7b3dff5d5291/href">https://medium.com/media/7841efe152fe89570f1a7b3dff5d5291/href</a></iframe><ul><li>This approach is better to implement when we want some data or payload inside the state to be persistent while the pages or widgets that consume the state are loaded.</li></ul><h4>Cons</h4><ul><li>There must be <strong>an extra enum class</strong>, in this case, MovieListStatus that is used to distinguish one state from another when dealing with getting data from the internet.</li><li>Because all <strong>data or payloads</strong> in the state can be accessed or exposed in any state. As an example from the above code, you can access the movieList data even when the state is not equal to success yet.</li></ul><h3>Multi-State Design</h3><p>The second approach is by creating a state class that <strong>has several derived classes</strong>, each of which is <strong>responsible for a specific state</strong> in the lifecycle of a page or a feature in the application and <strong>has specific data or payload</strong> needed in that particular state. Here’s an example of what this approach looks like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/12b8b68c15f45c47ecb1fa7996c3b324/href">https://medium.com/media/12b8b68c15f45c47ecb1fa7996c3b324/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a487a5436518f1cce3d110647241c2a0/href">https://medium.com/media/a487a5436518f1cce3d110647241c2a0/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bfe15b4af9e0db7b17633316b7ac1d4d/href">https://medium.com/media/bfe15b4af9e0db7b17633316b7ac1d4d/href</a></iframe><p>To access the state from either BlocConsumer, BlocListener, or BlocBuilder, it can be done in this way:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d5828fe4d608aa024d4aaee0e3a27049/href">https://medium.com/media/d5828fe4d608aa024d4aaee0e3a27049/href</a></iframe><h4>Optimization</h4><p>The above code can be simplified using freezed package that is responsible for generating the boilerplate like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8bc7ec4a56808bee32619b21a4a68f0b/href">https://medium.com/media/8bc7ec4a56808bee32619b21a4a68f0b/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f32b3df348dbe801f10502d97bd1f95c/href">https://medium.com/media/f32b3df348dbe801f10502d97bd1f95c/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2a11cd489d1124870756fb1f634c6910/href">https://medium.com/media/2a11cd489d1124870756fb1f634c6910/href</a></iframe><p>To access the state from either BlocConsumer, BlocListener, or BlocProvider, it can be done in this way:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/15246ed63987df52f63c963798b840de/href">https://medium.com/media/15246ed63987df52f63c963798b840de/href</a></iframe><h4>Pros</h4><ul><li>It’s resulting in <strong>more secure</strong> state management because each state has its <strong>data or payload</strong> which can only be accessed when that state is emitted.</li><li>This approach is better to implement when dealing with the process of getting data from the internet.</li></ul><h4>Cons</h4><ul><li>This approach is <strong>less effective</strong> if we want some data to be persistent as long as other data is changed in a certain state. Because <strong>when the state changes</strong>, the current <strong>data or payload</strong> inside the current state will be gone.</li></ul><h3>Summaries</h3><p>Those are some approaches that can be taken to design state management with Bloc in flutter development. Both approaches are valid and of course, have their advantages and disadvantages. You can make use of both in different cases.</p><p>I preferred to use the second approach while dealing with getting data from the internet and the first approach when dealing with some interactive state such as form validation.</p><p>I hope this article will be helpful. <strong>Thank you!</strong> 🙌🏼</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=972baa620dc4" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/how-to-design-an-effective-bloc-state-management-in-flutter-development-972baa620dc4">How to Design an Effective Bloc State Management in Flutter Development</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Provide Localizations Feature to a Flutter App with Bloc Library & Shared Preferences]]></title>
            <link>https://levelup.gitconnected.com/how-to-provide-localizations-feature-to-a-flutter-app-with-bloc-library-shared-preferences-2c2f4fc2fb8a?source=rss-8f67b6db7256------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c2f4fc2fb8a</guid>
            <category><![CDATA[flutter-bloc]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[localization]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Aditya Rohman]]></dc:creator>
            <pubDate>Sun, 22 Jan 2023 05:29:02 GMT</pubDate>
            <atom:updated>2023-07-30T17:46:22.003Z</atom:updated>
            <content:encoded><![CDATA[<h4>A comprehensive step-by-step of how to create app localizations in Flutter with the help of Bloc as the state management and Shared Preferences for caching the user language preference.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0AsRwKGcxBAOSAFa9ka_Ww.png" /></figure><p>A good user experience needs to be <strong><em>usable</em></strong>, <strong><em>equitable</em></strong>, <strong><em>enjoyable</em></strong>, and <strong><em>useful. </em></strong>If you are building an app and targeting broad users worldwide who speak different languages, you need to provide localizations which is one of the <strong><em>equitable</em></strong> aspects of UX.</p><p>Localizations means you provide your app in different languages (i.e. English, Bahasa Indonesia, etc). If you are consuming a RestAPI, it usually provides you responses in different language queries. But, this article will focus on providing app static localizations with built-in <strong>flutter_localizations</strong> package. To follow along, you can use a brand-new Flutter app or your previous Flutter projects.</p><h3>Step 1 — Setup Flutter Localizations</h3><p>Open the <strong>pubspec.yaml</strong> file and add the following packages:</p><pre>dependencies:<br>  flutter:<br>    sdk: flutter<br>  flutter_localizations: # Add this line<br>    sdk: flutter # Add this line<br>  intl: ^0.17.0 # Add this line</pre><p>Also, because we are going to provide our own localized texts then we need to add this line too:</p><pre>flutter:<br>  generate: true # Add this line</pre><p>The next step is to create a new folder inside <strong>lib</strong> where our localization files are stored. This folder is usually called <strong>l10n</strong> (which stands for localizations) or <strong>l18n</strong> (which stands for internationalization). That’s the commonly used name, but you can still use your own folder name.</p><p>Inside that folder, create a file with the <strong>.arb</strong> extension. In my case, I want to provide two languages to my app, English and Bahasa Indonesia. Then I create two files, <strong>app_en.arb</strong> and <strong>app_id.arb</strong>. Inside the <strong>.arb</strong> file, there are <strong><em>key-value pairs</em></strong> for the localized texts.</p><pre>{<br>  &quot;onboarding&quot;: &quot;The Easy Way\nTo Manage Your\nDaily Expense ✨&quot;,<br>  &quot;getStarted&quot;: &quot;Get Started&quot;,<br>  &quot;haveAccount&quot;: &quot;I Have Account&quot;<br>  ...<br>}</pre><pre>{<br>  &quot;onboarding&quot;: &quot;Cara Mudah\nAtur Pengeluaran\nHarian ✨&quot;,<br>  &quot;getStarted&quot;: &quot;Mulai&quot;,<br>  &quot;haveAccount&quot;: &quot;Saya Punya Akun&quot;<br>  ...<br>}</pre><p>To create a new localized text, all you need to do is add a new key-value pair inside the bracket. Neat!</p><p>Next, in the root project directory create a new <strong>.yaml</strong> file called <strong>l10n.yaml</strong> and add the following:</p><pre>arb-dir: lib/l10n # 1<br>template-arb-file: app_en.arb # 2<br>output-localization-file: app_localizations.dart # 3</pre><p>Here are what the above code does:</p><ol><li>Specified the localization location in the project. This will point to the folder that was created early, <strong>lib/l10n</strong>.</li><li>Specified the default language for the app when the user installs it for the first time. In this case, the default language is English (<strong>app_en.arb</strong>).</li><li>Specified the name of generated localization file. The commonly used name for that is <strong>app_localizations.dart</strong>, but you can use your own name for more convenience.</li></ol><p>To start generating the localizations, build and run the app or run the command below in the terminal:</p><pre>flutter gen-l10n</pre><p>This will generate the localizations files like so:</p><pre>.dart_tool<br>├── flutter_gen<br>│   ├── gen_l10n<br>│   │   ├── <strong>app_localizations.dart &lt;--</strong><br>│   │   ├── <strong>app_localizations_en.dart &lt;--</strong><br>│   │   └── <strong>app_localizations_id.dart &lt;--</strong><br>│   └── pubspec.yaml<br>...</pre><p>After that, open <strong>lib/main.dart</strong> and set the<strong>supportedLocales</strong> and <strong>localizationsDelegates</strong> properties of <strong>MaterialApp</strong> with the generated localizations code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/240c892a92ef02f3717ec75824cf8799/href">https://medium.com/media/240c892a92ef02f3717ec75824cf8799/href</a></iframe><p>Finally, the localized texts are ready to use. To access the localized texts, use the following syntax:</p><pre>AppLocalizations.of(context)!.&lt;YOUR_TEXT_KEY&gt;</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bd0fcf7b6acd47932d500a30dc9c4926/href">https://medium.com/media/bd0fcf7b6acd47932d500a30dc9c4926/href</a></iframe><p>For more information and best practices about <strong>flutter_localizations</strong>, read the official Flutter documentation here:</p><p><a href="https://docs.flutter.dev/development/accessibility-and-localization/internationalization">Internationalizing Flutter apps</a></p><h3>Step 2 — Create Real-Time Language Changes using Bloc Library</h3><p>So far we’ve set up the localizations. The next thing we need to do is provide the users with in-app language settings so the users can choose their preferred language. This can be achieved using <strong>state management</strong>. In this article, we’ll be using <strong>Bloc Library</strong>. Make sure you’ve already familiar with <strong>Bloc state management</strong> implementation to follow along. If you are new to <strong>Bloc</strong>, then you can read the documentation first.</p><p><a href="https://bloclibrary.dev/#/gettingstarted">Bloc State Management Library</a></p><p>To make things simple, we can use an <strong><em>enhanced enum</em></strong>, which was introduced on Dart 2.17. So, make sure you use SDK version 2.17 or above. You can read more about enhanced enums here:</p><p><a href="https://dart.dev/guides/language/language-tour#enumerated-types">A tour of the Dart language</a></p><p>Create a new file called <strong>language.dart</strong> and add the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e49b771fb0466524e7b78e0f1e5bbb77/href">https://medium.com/media/e49b771fb0466524e7b78e0f1e5bbb77/href</a></iframe><p>Next, create a new <strong>bloc</strong> to handle the app language change.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/493138fb8941b3823ad6ce4ff196c238/href">https://medium.com/media/493138fb8941b3823ad6ce4ff196c238/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/687eb8cea93d44cc662e297791cc7a98/href">https://medium.com/media/687eb8cea93d44cc662e297791cc7a98/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3dc7d21d251a3509382601ffb7f835b1/href">https://medium.com/media/3dc7d21d251a3509382601ffb7f835b1/href</a></iframe><p>Now, you can use that bloc in your app. Here is my implementation for the example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/77efa165f6639b660b262fec2f918dca/href">https://medium.com/media/77efa165f6639b660b262fec2f918dca/href</a></iframe><p>Here, we wrap the <strong>MaterialApp</strong> with <strong>BlocBuilder</strong> to rebuild the widget tree when the state changes. Also, don’t forget to register the bloc with <strong>BlocProvider</strong>. Then, set the <strong>locale</strong> property with the state value.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d655525523ab93531fdcb69aa429fd66/href">https://medium.com/media/d655525523ab93531fdcb69aa429fd66/href</a></iframe><p>In the code above, we trigger the state changes using the following syntax:</p><pre>context.read&lt;LanguageBloc&gt;().add(ChangeLanguage(selectedLanguage: Language.values[index]));</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*JWFlvPQ19JNIV5MYBIYVGA.gif" /></figure><h3>Step 3 — Save User Language Preference using Shared Preferences</h3><p>We have implemented app localizations successfully, but something is still missing. If you change the app language to your preferred one, then hit the <strong><em>hot reload</em></strong>, guess what happens here? Yes, the language is back to default, in this case, English. To solve this problem, all we need to do is to cache the user&#39;s preferred language using <strong>shared_preferences</strong>.</p><p><a href="https://pub.dev/packages/shared_preferences">shared_preferences | Flutter package</a></p><p>Open the <strong>pubspec.yaml</strong> file and add the package.</p><pre>shared_preferences: ^2.0.17</pre><p>Next, we need to modify our <strong>bloc</strong>. First, add a new <strong>bloc event</strong> to retrieve the cached language preference:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/89066e6d54876f2bcb1d7c161500184f/href">https://medium.com/media/89066e6d54876f2bcb1d7c161500184f/href</a></iframe><p>After that, update the LanguageBloc with the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d6f65f118a0b5329227fbddf3bf0a9c/href">https://medium.com/media/9d6f65f118a0b5329227fbddf3bf0a9c/href</a></iframe><p>Here are what the above code does:</p><ol><li>When the user changes their preferred language, store it in the shared preference, then emit the state changes.</li><li>When the user opens the app, loads the preferred language from the shared preference, then emits the state changes. If the user opens the app for the first time, which means the shared preferences are currently <strong><em>null</em></strong>, then provide the default language.</li></ol><p>Lastly, update the <strong>BlocProvider</strong> inside <strong>main.dart</strong> with the following:</p><pre>create: (context) =&gt; LanguageBloc()<strong>..add(GetLanguage())</strong>,</pre><p>Try to run the app again, change the language and then hit <strong><em>hot reload</em></strong>. Now, the app language doesn’t return to the default language again. Great!</p><p>So, that is a simple approach to implementing app localizations on a Flutter app. Hope this will be helpful. You can see the full code below. Thank you!</p><p><a href="https://github.com/codestronaut/expense_tracker">GitHub - codestronaut/expense_tracker: [Flutter Personal Project] - A mobile app to track daily expense and get monthly expense analytics. Created with Flutter and backed by Firebase.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c2f4fc2fb8a" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/how-to-provide-localizations-feature-to-a-flutter-app-with-bloc-library-shared-preferences-2c2f4fc2fb8a">How to Provide Localizations Feature to a Flutter App with Bloc Library &amp; Shared Preferences</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Easy Way to Create a Good Error-Handling in Flutter With Dartz]]></title>
            <link>https://medium.com/better-programming/easiest-way-to-create-a-good-error-handling-in-flutter-with-dartz-44084d5341bb?source=rss-8f67b6db7256------2</link>
            <guid isPermaLink="false">https://medium.com/p/44084d5341bb</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Aditya Rohman]]></dc:creator>
            <pubDate>Fri, 06 May 2022 07:50:03 GMT</pubDate>
            <atom:updated>2022-05-07T04:17:14.861Z</atom:updated>
            <content:encoded><![CDATA[<h4>Don’t make your user confused, create a good error-handling when developing an app</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*INRKPrr_K0unchVAcPi3Ng.png" /></figure><p>As developers, our main task is to create applications to solve certain problems. When published, the application we develop may produce some errors in front of the user. For example, maybe our users enter data incorrectly, the connection is lost, or even our server is down.</p><p>A good application will be able to handle the error and can point the user on the right path again. We certainly don’t want just because the app can’t handle minor errors like lost connection, the user decides to uninstall it.</p><p>In this article, I will show how to create good error handling in a Flutter project using Dartz.</p><p><a href="https://pub.dev/packages/dartz">dartz | Dart package</a></p><h3>Implementation</h3><p>First things first, we need to figure out what errors are possible that will happen. In a login flow, for example, the common error is:</p><ul><li>User inputs wrong password or email not registered</li><li>The server maybe had a problem</li><li>Lost internet connection</li></ul><p>Now, let’s add the package that we need to the pubspec.yaml file:</p><pre>...<br>dependencies:<br>    flutter:<br>        sdk: flutter<br>    <br>    dartz: ^0.10.1<br>    ...</pre><p>Inside the Dartz package, we will use something called Either&lt;L,R&gt; class. This class will be used to return 2 different things in a function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e647235ab2900672ad5d50575fafe7fd/href">https://medium.com/media/e647235ab2900672ad5d50575fafe7fd/href</a></iframe><p>There is a function with the type Future&lt;<strong>Either&lt;LoginFailure, bool&gt;</strong>&gt;. With that type, now I can return 2 different things out of that function.</p><p>When the request is successful (with status code 200), boolean true will be returned as the right value.</p><p>If a request failed, I can easily handle it by returning the enum as the left value. The enum class act as a helper to create conditions.</p><p>And this is the way we consume the login function, for example in a controller:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/98c0d82c65ece431375aaf13b53d1ad0/href">https://medium.com/media/98c0d82c65ece431375aaf13b53d1ad0/href</a></iframe><p>Now you can create some user interactions like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4tPnVTuF07FKNvOICXnPbg.png" /><figcaption>Example user interactions to handle some errors</figcaption></figure><h3>Recap</h3><p>So, that&#39;s the way to implement a good error-handling on Flutter. The term good means our app has more rich error-handling to help the user understand if there is something wrong when they use the app.</p><p>Thanks for reading. I hope these short tips can help you write a more clean, concise, and robust codebase for your Flutter project.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=44084d5341bb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/easiest-way-to-create-a-good-error-handling-in-flutter-with-dartz-44084d5341bb">Easy Way to Create a Good Error-Handling in Flutter With Dartz</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Write Unit Tests for Appwrite SDK on Flutter With Mockito]]></title>
            <link>https://medium.com/better-programming/write-unit-test-for-appwrite-sdk-on-flutter-with-mockito-e0c3b403199e?source=rss-8f67b6db7256------2</link>
            <guid isPermaLink="false">https://medium.com/p/e0c3b403199e</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Aditya Rohman]]></dc:creator>
            <pubDate>Thu, 05 May 2022 07:03:48 GMT</pubDate>
            <atom:updated>2022-05-06T14:12:49.562Z</atom:updated>
            <content:encoded><![CDATA[<h3>Easy Step to Unit Test Appwrite SDK on Flutter with Mockito</h3><h4>A practical guide to writing unit tests for Appwrite SDK on Flutter with Mockito</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5-qovIN6dcWiJBxJNH-5Ig.png" /></figure><p><a href="https://appwrite.io/">Appwrite</a> is an open-source (OSS) Backend as a Service that is aiming to abstract the complexity of common, complex, and repetitive tasks required for building a modern app. Appwrite can be used as an alternative to Firebase with a bunch of features like authentications, database, storage, functions, and real-time support. Also, it provides SDK for almost all platforms like web, Android, iOS, Flutter, etc.</p><p>Although we using SDK for developing an app. Unit testing is still important to do to test if our app is connected well or not to that SDK. So, in this article, I want to show you how to create a unit test on your Flutter project when using Appwrite as the SDK for your backend.</p><p>If you are new to term unit testing, you can read my previous article about <a href="https://betterprogramming.pub/flutter-testing-101-understand-unit-widget-and-integration-testing-fd5d07e312e">Flutter testing here</a>.</p><h4>Step 1 — Get Mockito Plugin</h4><p>Because in a unit test we don’t execute a real function. So, to be able to unit test a service like Appwrite is that we need to create a mock for that service. To do that we need a plugin called Mockito</p><p><a href="https://pub.dev/packages/mockito">mockito | Dart package</a></p><p>Let’s add mockito to our dev_dependencies on pubspec.yaml file.</p><pre>...<br>dev_dependencies:<br>    flutter_test:<br>        sdk: flutter</pre><pre>    build_runner: ^2.1.7<br>    mockito: ^5.1.0<br>...</pre><p>Besides mockito, we also need build_runner it because mockito will generate the mock file.</p><p><a href="https://pub.dev/packages/build_runner">build_runner | Dart package</a></p><h4>Step 2 — Create Appwrite Mock</h4><p>After getting the plugins we need, the next step is to generate a mock of our service. For example, I want to create a repository for authentication stuff. So, I will generate a mock for the Account from Appwrite SDK.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0175c2ac13c72c85ed472c03a4633050/href">https://medium.com/media/0175c2ac13c72c85ed472c03a4633050/href</a></iframe><p>To generate a new mock file, we use @GenerateMocks() annotation on our test file. After that, we need to run build_runner to start generating the mock file. This command will generate a new file like auth_repository_test.mocks.dart</p><pre>flutter packages pub run build_runner build</pre><h4>Step 3 — Write Test</h4><p>Now, we are ready to write our test. As an example, I will write a test for the login function. Here is what my test file for auth_repository_test.dart looks like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/12e1887ff04de735ebe906c8d602b3bf/href">https://medium.com/media/12e1887ff04de735ebe906c8d602b3bf/href</a></iframe><p>MockAccount is taken from the mock file that we generated previously. On the AuthRepositoryImpl, I pass the _mockAccount as the dependency.</p><h4>Step 4 — Write Actual Code</h4><p>The last step is to write the actual repository code. Here is what my auth_repository.dart file looks like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d17b8d5ca30c74a9a502365e99dc766/href">https://medium.com/media/3d17b8d5ca30c74a9a502365e99dc766/href</a></iframe><p>By the way, Appwrite also provides AppwriteException class. It’s helpful if you want to create more rich error handling for your app. For example, wrong password warning, email already in use warning, etc.</p><p>So, that&#39;s a step-by-step writing unit testing for your Flutter project when you use Appwrite as the SDK for making your life easier while creating an app solo. I use Test-Driven Development method when writing that unit test. If you are curious about TDD, you can read more here:</p><p><a href="https://betterprogramming.pub/flutter-clean-architecture-test-driven-development-practical-guide-445f388e8604">Power Up Your Flutter Development Process by Implementing Clean Architecture and Test-Driven…</a></p><p>If you have any questions, feel free to start a discussion.</p><p>Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e0c3b403199e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/write-unit-test-for-appwrite-sdk-on-flutter-with-mockito-e0c3b403199e">Write Unit Tests for Appwrite SDK on Flutter With Mockito</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Testing— Understand Unit, Widget, and Integration Testing]]></title>
            <link>https://medium.com/better-programming/flutter-testing-101-understand-unit-widget-and-integration-testing-fd5d07e312e?source=rss-8f67b6db7256------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd5d07e312e</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Aditya Rohman]]></dc:creator>
            <pubDate>Sun, 06 Feb 2022 15:09:47 GMT</pubDate>
            <atom:updated>2022-02-07T06:23:18.512Z</atom:updated>
            <content:encoded><![CDATA[<h4>A practical guide to common testing types in Flutter such as unit testing, widget testing, and integration testing.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xDwF45hIwIbQG-IEDJ7p0w.png" /><figcaption>Photo by <a href="https://unsplash.com/@balazsketyi?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Balázs Kétyi</a> on <a href="https://unsplash.com/s/photos/mobile-app?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Testing is important when developing a product in the form of an application. By implementing testing, we will become more confident when releasing the product or application to the public because we can ensure the application that we developed runs as expected and has fewer bugs.</p><h3>Type of Testing in Flutter</h3><p>There are 3 types of testing methods that are commonly implemented in a Flutter project:</p><h4>Unit Testing</h4><p>Unit testing is a type of testing on an application where testing is focused on what is called a unit. Unit is the smallest part that builds up the application. The simplest examples of units when we talk about OOP (Object-Oriented Programming) are Class and Function. Unit testing will ensure that small components of an application run well and as expected.</p><p>To perform unit testing we use the following function:</p><pre>test(&#39;description&#39;, () {});</pre><p>Example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bae8bef747316b64953d2d090b6d444a/href">https://medium.com/media/bae8bef747316b64953d2d090b6d444a/href</a></iframe><p>In the code above, we try to do a unit test for data source movie_remote_data_source.dart to get movies data from the API. There are two scenarios: (1) when data from the API is successfully retrieved and (2) when data from the API fails to be retrieved.</p><p>One block of testing code generally consists of 3 parts:</p><ul><li><strong>Arrange —</strong> the stage where we prepare the object or configuration for our testing. In the example above, we set up a mock HTTP Client object to simulate getting data from API in testing.</li></ul><blockquote><strong>Mocking</strong> is creating a mock object so that it can be used for testing without having to think about the dependencies of the object with other objects in the project.</blockquote><p>Here are the libraries that are commonly used for mocking:</p><ul><li><a href="https://pub.dev/packages/mockito">mockito | Dart package</a></li><li><a href="https://pub.dev/packages/mocktail">mocktail | Dart package</a></li></ul><ul><li><strong>Act —</strong> the stage where we call the function we want to test. In the example above, we call the getNowPlayingMovies() function that is in the MovieRemoteDataSourceImpl class.</li><li><strong>Assert — </strong>the stage where we validate the action that has been executed whether it is in accordance with what is expected or not. In the above example, when the data is successfully retrieved from the API we validate the result of the getNowPlayingMovies() function call is equal to the movie list.</li></ul><h4>Widget Testing</h4><p>Widget testing or in other terms called <strong>instrumentation testing</strong> is a type of testing that is focused on the parts that build the User Interface of an application such as buttons, text fields, and so on. Widget testing will ensure that the User Interface is laid out according to the UI design of the application and can interact well with the user.</p><p>To perform widget testing we use the following function:</p><pre>testWidgets(&#39;description&#39;, (WidgetTester tester) {});</pre><p>Example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9ad6487398eeeff9ad53f8786ac6d69e/href">https://medium.com/media/9ad6487398eeeff9ad53f8786ac6d69e/href</a></iframe><p>The process for widget testing is still the same as for unit testing (arrange, act, and assert). The difference is that here we are testing part of the User Interface (widget) of the application. In the example above, we tested whether when the user adds a movie to the watchlist by pressing the save watchlist button a snack bar will appear.</p><p>When our application implements state management such as provider, BLoC, and others, we need to declare it also during the pump widget process.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e25a2c817900ed374646781d0f5c6cb4/href">https://medium.com/media/e25a2c817900ed374646781d0f5c6cb4/href</a></iframe><h4>Integration Testing</h4><p>Integration testing is a type of testing that is focused on testing the entire flow of the application (end-to-end testing). To run integration testing, you need an emulator or real device. During testing, the application will appear on the emulator or real device and run the application automatically.</p><p>Integration testing is very helpful for testing how a feature or entire application runs during the development process. It will be more efficient than we have to run the application and test the features or the entire application manually.</p><p>To implement integration testing, we need to add the library to pubspec.yaml.</p><pre>dev_dependencies:    <br>    ...<br>    <strong>integration_test:       <br>        sdk: flutter</strong></pre><p>Then in the project directory, we need to create a new folder called integration_test. Examples are as follows:</p><pre><strong>integration_test</strong><br>├── app_test.dart<br>└── robots<br>    ├── home_robot.dart<br>    └── ...</pre><p>In that folder is there is app_test.dart which contains all the end-to-end testing scenarios for our application. Then there is also a robots folder that contains each testing scenario. Application testing scenarios can be separated (eg by page).</p><p>Example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/edc7b36ab3fedc8742ec70f78c061977/href">https://medium.com/media/edc7b36ab3fedc8742ec70f78c061977/href</a></iframe><p>In home_robot.dart above, we create a test scenario for the home page of the application. An example is opening the drawer when pressing the menu button on the AppBar.</p><p>To be able to access the widget we are aiming for, we can use Key() function. So we have to register a key on the widget that we want to test. Examples are as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/42c927bdbbe6e1910f10a0a60f2970af/href">https://medium.com/media/42c927bdbbe6e1910f10a0a60f2970af/href</a></iframe><p>Then we can combine all scenarios into app_test.dart.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/13292b166f6e130ec70ac48a0a5a9e84/href">https://medium.com/media/13292b166f6e130ec70ac48a0a5a9e84/href</a></iframe><p>In the code above, we first call IntegrationTestWidgetsFlutterBinding.ensureInitialized() function to make sure the page of our app is ready for testing.</p><p>To run integration testing, set up an emulator or real device. After that, run the following command on the terminal:</p><pre>flutter test integration_test</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/0*gsJkg5uGtmpm8Tub.gif" /><figcaption>Integration testing result</figcaption></figure><h3>Recap</h3><p>In conclusion, when developing an application, consider testing as much as possible. So that the final results of the application can be measured properly and facilitate maintenance when there are features that you want to revamp or fix.</p><p>Full source code:</p><p><a href="https://github.com/codestronautHub/flutter-movie-database-app">GitHub - codestronautHub/flutter-movie-database-app: This is a movie catalog app. The main feature is movies dan tv shows list, watchlists, and many more. This app is powered by TMDB (The Movie DB)</a></p><p>So that’s a little discussion about testing on the Flutter application project, hopefully, it is helpful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd5d07e312e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/flutter-testing-101-understand-unit-widget-and-integration-testing-fd5d07e312e">Flutter Testing— Understand Unit, Widget, and Integration Testing</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Power Up Your Flutter Development Process by Implementing Clean Architecture and Test-Driven…]]></title>
            <link>https://medium.com/better-programming/flutter-clean-architecture-test-driven-development-practical-guide-445f388e8604?source=rss-8f67b6db7256------2</link>
            <guid isPermaLink="false">https://medium.com/p/445f388e8604</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Aditya Rohman]]></dc:creator>
            <pubDate>Sat, 05 Feb 2022 05:31:09 GMT</pubDate>
            <atom:updated>2022-02-06T15:31:26.131Z</atom:updated>
            <content:encoded><![CDATA[<h3>Power Up Your Flutter Development Process by Implementing Clean Architecture and Test-Driven Development</h3><h4>The complete process to set up clean architecture in a Flutter codebase</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-N7TbKkCsbtKztuhebyGSw.png" /><figcaption>Photo by <a href="https://unsplash.com/@ryanancill?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Ryan Ancill</a> on <a href="https://unsplash.com/s/photos/floor-plan?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Since being released to the public on December 4, 2018, the application development ecosystem with Flutter has experienced very rapidly. Choosing Flutter as the SDK for developing products with fast iterations is the right choice. However, when choosing Flutter, developers should also start thinking about how to organize the state management of the app and how to design the app (behind the scenes) to be maintainable and scalable.</p><p>To address these concerns, we need to design the architecture of the application before starting to develop the features.</p><h3>Clean Architecture</h3><p>Architecture is very important in developing an application. Architecture can be likened to a floor plan that describes how the flow in an application project. The main purpose of implementing the architecture is the separation of concern (SoC). So, it will be easier if we can work by focusing on one thing at a time.</p><p>In the context of Flutter, clean architecture will help us to separate code for business logic with code related to platforms such as UI, state management, and external data sources. In addition, the code that we write can be easier to test (testable) independently.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KtSvmSz5XOeSTeBWEjUeXg.png" /><figcaption>Clean Architecture Diagram</figcaption></figure><p>As in the diagram above, the clean architecture is depicted as a pyramid or a slice of onion when viewed from the top. The clean architecture will divide the Flutter project into 3 main layers, namely:</p><h4>Data &amp; Platform layer</h4><p>The data layer is located at the outermost layer. This layer consists of data source code such as consume Rest API, access to the local database, Firebase, or other sources. Also, on this layer, there is usually the platform code that builds up the UI (widgets).</p><h4>Presentation Layer</h4><p>The presentation layer consists of the code to access the data of the app from a repository. Also, there is the code for state management such as providers, BLoC, and so on.</p><h4>Domain Layer</h4><p>The domain layer is the deepest in the clean architecture. This layer contains the code for business logic applications such as entities and use cases.</p><blockquote>Each layer depends on the other layers. The arrows on the diagram show how the layers are related. The outermost layer will depend on the inner layer and so on.</blockquote><p>The layer that does not depend on any other layers here is only the domain layer (independent) which is the code for the business logic. That way, the application is more adaptable and dynamic. For example, if we want to change the state management from the provider to BLoC, the migration process will not interfere with the existing business logic.</p><h3>Test-Driven Development</h3><p>In addition to implementing the clean architecture, to optimize the development process in terms of producing minimal bugs and reducing repetitive debugging and fixing processes, we must undergo a testing process.</p><p>Test-Driven Development is an application development process where testing is the main character that drives the development. Testing code scenarios will be written first before creating a feature in the application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h4aHudsWKs3QyERchcNnBg.png" /><figcaption>Test-Driven Development Workflow</figcaption></figure><p>The workflow of the application development process with TDD is as shown in the diagram above. Note that the TDD process is iterative and it’s called the Red-Green-Refactor process.</p><h4>Step — 1: Write testing scenarios (Red)</h4><p>The development of a feature begins with writing a test scenario first. Writing test scenarios usually follows the feature requirements in a PRD document (for the case in a company). In the test scenario, there will usually be a flow of the developed features such as determining the data source used (eg remote or local), ensuring the incoming data from the API produces the appropriate model, designing the state flow of the view based on the data, and so on. . The first time we write a test scenario, we will get errors. This is normal because the feature code does not yet exist.</p><blockquote>Writing a test scenario for a feature is done as a guide in developing the feature (actual code).</blockquote><h4>Step — 2: Make the testing scenarios successful (Green)</h4><p>In this step, the actual feature code writing is done. Writing code at this stage does not have to be neat and optimal because the main goal in this step is to make the testing code that has been made previously successful.</p><h4>Step — 3: Refactor the code</h4><p>After the testing code has been successfully run without any errors, it is time to tidy up and optimize the code that has been written, both testing code and actual feature code.</p><p>With the TDD process, the final result that will be obtained is in addition to an application that has minimal bugs, as well as a neat and optimal application code.</p><h3>Case Study Implementation</h3><p>Now, we will try to implement the 2 concepts we talked about earlier in a mini-project, namely a weather application. This time we will use the <a href="https://openweathermap.org/api">OpenWeather API</a> as the data source of our application.</p><p>The folder structure of this project will look like this:</p><pre>lib<br>├── data<br>│   ├── constants.dart<br>│   ├── datasources<br>│   │   └── remote_data_source.dart<br>│   ├── exception.dart<br>│   ├── failure.dart<br>│   ├── models<br>│   │   └── weather_model.dart<br>│   └── repositories<br>│       └── weather_repository_impl.dart<br>├── domain<br>│   ├── entities<br>│   │   └── weather.dart<br>│   ├── repositories<br>│   │   └── weather_repository.dart<br>│   └── usecases<br>│       └── get_current_weather.dart<br>├── injection.dart<br>├── main.dart<br>└── presentation<br>    ├── bloc<br>    │   ├── weather_bloc.dart<br>    │   ├── weather_event.dart<br>    │   └── weather_state.dart<br>    └── pages<br>        └── weather_page.dart</pre><pre>test<br>├── data<br>│   ├── datasources<br>│   │   └── remote_data_source_test.dart<br>│   ├── models<br>│   │   └── weather_model_test.dart<br>│   └── repositories<br>│       └── weather_repository_impl_test.dart<br>├── domain<br>│   └── usecases<br>│       └── get_current_weather_test.dart<br>├── helpers<br>│   ├── dummy_data<br>│   │   └── dummy_weather_response.json<br>│   ├── json_reader.dart<br>│   ├── test_helper.dart<br>│   └── test_helper.mocks.dart<br>└── presentation<br>    ├── bloc<br>    │   └── weather_bloc_test.dart<br>    └── pages<br>        └── weather_page_test.dart</pre><p>If you want to follow this tutorial, you can use the following starter code on this <a href="https://github.com/codestronaut/flutter-weather-app-sample.git">Github repository</a>.</p><h4>Step — 1: Writing code on the domain layer</h4><p>The first step is to write code at the domain layer. Why the domain layer? because this layer is a layer that does not depend on any other layer. So it will be safer if you start from this layer.</p><h4>Usecases</h4><p>In the test/domain section, we only need to write test scenarios for use cases. In this case, we have 1 use case, get_current_weather_test.dart.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7bcf51c857063aa5cc042aba7cad8532/href">https://medium.com/media/7bcf51c857063aa5cc042aba7cad8532/href</a></iframe><blockquote>The test code above will have an error at the beginning. This is normal because we haven’t written the actual code yet.</blockquote><p>For actual feature code at the domain layer, there are 3 parts, namely entities, use cases, and repositories. We start by writing the weather entity which is the weather.dart</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aa74aa8ea5a6c708f9db70a0887c7a54/href">https://medium.com/media/aa74aa8ea5a6c708f9db70a0887c7a54/href</a></iframe><p>After that, we continue by writing code for weather_repository.dart. The weather repository is an abstract class and will be implemented later at the data layer.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d39fd7028dd23b90a96d9d8b9b05f866/href">https://medium.com/media/d39fd7028dd23b90a96d9d8b9b05f866/href</a></iframe><p>Then, we will write code for the use case get_current_weather.dart.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/634ea5ae864b0331e468761680afce69/href">https://medium.com/media/634ea5ae864b0331e468761680afce69/href</a></iframe><p>Before going back to testing code, we have to create a mock weather repository. Open test_helper.dart and add WeatherRepository. In test _helper.dart there is also a mock for the HTTP library so that it can simulate requests to the API during testing.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/33ce357b2db5b64c13175c9e24ae0cf3/href">https://medium.com/media/33ce357b2db5b64c13175c9e24ae0cf3/href</a></iframe><p>Run the following command via the terminal to generate the mock file:</p><pre>flutter pub run build_runner build</pre><p>After that, go back to the get_current_weather_test.dart and import the MockWeatherRepository then runs the test.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/436/0*gE8hZZbEf6UMOZpl.png" /><figcaption>Get current weather use case test result</figcaption></figure><h4>Step — 2: Writing code on the data layer</h4><p>After working on the testing code and features at the domain layer, we can now move on to working on the code at the data layer. At the data layer, there are data sources, models, and repositories.</p><blockquote>Wait a minute, is there a repository at the domain layer too? Yes, the repository at the domain layer is in the form of an abstract class in which there are functions that still need to be implemented. So, it is in the repository at the data layer that we will start implementing the abstract class.</blockquote><h4>Models</h4><p>Ok, we will start with models, the process begins by writing testing code for the model, weather_model_test.dart. Here, we will test 3 main things:</p><ul><li>Is the model that we have created equal with the entities at the domain layer?</li><li>Does the fromJson() function return a valid model?</li><li>Does the toJson() function returns the appropriate JSON map?</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d760726e0ef2c69002e5c2123c6388d4/href">https://medium.com/media/d760726e0ef2c69002e5c2123c6388d4/href</a></iframe><p>Then, we continue by writing the code for weather_model.dart</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/94b8f67505a6d6de9c9bd644275b97f1/href">https://medium.com/media/94b8f67505a6d6de9c9bd644275b97f1/href</a></iframe><p>After that, go back to the testing code and import weather_model.dart then runs the test.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/0*H6iBDr4V7MwAY-GC.png" /><figcaption>Model testing result</figcaption></figure><h4>Data Sources</h4><p>We continue with working on the code in the data sources. Here is the code for remote_data_source_test.dart.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/70d4114d5e2e13f9c64dff8722f7fcc6/href">https://medium.com/media/70d4114d5e2e13f9c64dff8722f7fcc6/href</a></iframe><p>The above remote_data_source_test.dart code will test the process of getting weather data from the API. There are two conditions:</p><ul><li>Returning a valid model when getting data is successful</li><li>Returning a ServerException when getting data is failed</li></ul><p>We also need dummy data in JSON form like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c39cef0d32d29ed29b9cad4e2b67c63/href">https://medium.com/media/0c39cef0d32d29ed29b9cad4e2b67c63/href</a></iframe><p>Then continue by writing the code for the data source, remote_data_source.dart.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b09f976325221a43a1fab89e27cb7272/href">https://medium.com/media/b09f976325221a43a1fab89e27cb7272/href</a></iframe><p>After that, go back to the testing code and import remote_data_source.dart then runs the test.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/0*T29lt2PCzuvKKpL5.png" /><figcaption>Data sources testing result</figcaption></figure><h4>Repositories</h4><p>Next, we will work on the code for the repository, namely weather_repository_impl_test.dart and weather_repository_impl.dart. The term impl here means implementation.</p><p>For testing on weather_repository_impl_test.dart we need to access the data source. So, we will first generate a mock for the remote data source that we created earlier. Add RemoteDataSource to test_helper.dart as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/861cf79a2602aa7966e4cdf8f94cb4dd/href">https://medium.com/media/861cf79a2602aa7966e4cdf8f94cb4dd/href</a></iframe><p>Then, run the following <strong>command</strong> to generate a mock from the data source:</p><pre>flutter pub run build_runner build</pre><p>Now, the MockRemoteDataSource is ready to use for testing, now we work on the code for weather_repository_impl_test.dart.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c105263b4743c0109c28fc735e74d9d4/href">https://medium.com/media/c105263b4743c0109c28fc735e74d9d4/href</a></iframe><p>In the code above the scenarios tested are:</p><ul><li>Returns current weather data on successful API request</li><li>Returns ServerFailure when the request to API fails</li><li>Restore ConnectionFailure when not connected to the internet</li></ul><p>Now let’s continue with working on weather_repository_impl.dart.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/67217f3fd044f1f723f8845665d48029/href">https://medium.com/media/67217f3fd044f1f723f8845665d48029/href</a></iframe><p>After that, go back to the testing code and import weather_repository_impl.dart then runs the test.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/0*9A8AdwQsGjptIt9K.png" /><figcaption>Repository testing result</figcaption></figure><h4>Step — 3: Writing code on the presentation layer</h4><p>After working on the domain and data layers, the final step is working on the code at the presentation layer. At this layer, there are state management (in this case we use <em>BLoC</em>), and pages.</p><h4>State management (<em>BLoC</em>)</h4><p>First, we will code state management (<em>BLoC</em>). For testing on weather_bloc_test.dart, we need to access the use case which is MockGetCurrentWeather.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/967f14a1dd119186db8dac70ed8ae113/href">https://medium.com/media/967f14a1dd119186db8dac70ed8ae113/href</a></iframe><p>Then run the following command to generate a mock from GetCurrentWeather.</p><pre>flutter pub run build_runner build</pre><p>Then, we continue by working on the <em>BLoC</em> state management code. Here our <em>BLoC</em> code consists of weather_state.dart, weather_event.dart, and weather_bloc.dart.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3310a2f7713c3a750bcc4605ac25c789/href">https://medium.com/media/3310a2f7713c3a750bcc4605ac25c789/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7d2069350b644ebdbb21fe786af457d9/href">https://medium.com/media/7d2069350b644ebdbb21fe786af457d9/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5a9920ee33157a7a1fa976321617953a/href">https://medium.com/media/5a9920ee33157a7a1fa976321617953a/href</a></iframe><p>After that, go back to the testing code and import weather_bloc.dart then runs the test.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/0*Y6ZNCGRNpztjyogB.png" /><figcaption>BLoC state management testing result</figcaption></figure><h4>Pages</h4><p>After working on the <em>BLoC</em> code, then we will create code for the pages or UI of the application. Let’s start with the testing code, namely weather_page_test.dart. Here, we will test 3 things:</p><ul><li>The state of the app should change from WeatherEmpty to WeatherLoading when it’s finished fill the TextField.</li><li>Displays a progress indicator when the state of the application is WeatherLoading.</li><li>Displays a widget containing weather information when the state of the application is WeatherHasData.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bcbfae826bcc4adf9314ba04eb9fa143/href">https://medium.com/media/bcbfae826bcc4adf9314ba04eb9fa143/href</a></iframe><p>Then, we continue by writing the code for weather_page.dart.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9ecab4bca2cfe78c4a37d9db3ddf93e8/href">https://medium.com/media/9ecab4bca2cfe78c4a37d9db3ddf93e8/href</a></iframe><p>After that, go back to the testing code and import weather_page.dart then runs the test.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/0*Ku5h-CEMysreQDfh.png" /><figcaption>Page testing result</figcaption></figure><h3>Run the app</h3><p>At this point, we have completed the application with one feature, which is getting the latest weather information based on the search for city names. Now, we will try to run the application on the emulator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Pz5FoVgJFjQd9p6J.png" /><figcaption>Final result</figcaption></figure><h3>Recap</h3><p>The process of implementing Test-Driven Development and clean architecture is indeed quite complex. However, if we rely on the final result, namely minimal bugs, ease of adding features, and library migration (such as state management), it’s worth it!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F7xo5HwHZGWrbxHriEJ%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F7xo5HwHZGWrbxHriEJ%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F7xo5HwHZGWrbxHriEJ%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="435" frameborder="0" scrolling="no"><a href="https://medium.com/media/4032fe57ae33d1ca690a9120b40f2688/href">https://medium.com/media/4032fe57ae33d1ca690a9120b40f2688/href</a></iframe><p>Finally, we can run test coverage to see if all the code has been tested. Run the following command in the project directory in the terminal:</p><pre>flutter test --coverage<br>genhtml coverage/lcov.info -o coverage/html<br>open coverage/html/index.html</pre><p>And, this is the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*appZ7n1L9Tt1tSjH.png" /><figcaption>Test coverage result</figcaption></figure><p>So, that’s the process of implementing Clean architecture and Test-Driven Development in the Flutter project. Hope it is useful. Thank you!</p><p>The completed code:</p><p><a href="https://github.com/codestronaut/flutter-weather-app-sample.git">GitHub - codestronaut/flutter-weather-app-sample: This repository is a sample app for learning TDD and clean architecture in action!</a></p><h3>References</h3><ul><li><a href="https://ieeexplore.ieee.org/abstract/document/9071367">https://ieeexplore.ieee.org/abstract/document/9071367</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=445f388e8604" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/flutter-clean-architecture-test-driven-development-practical-guide-445f388e8604">Power Up Your Flutter Development Process by Implementing Clean Architecture and Test-Driven…</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Testing 101 — Memahami Unit Testing, Widget Testing, dan Integration Testing pada Flutter]]></title>
            <link>https://aditya-rohman.medium.com/memahami-testing-pada-project-aplikasi-flutter-71b6859b4cd4?source=rss-8f67b6db7256------2</link>
            <guid isPermaLink="false">https://medium.com/p/71b6859b4cd4</guid>
            <category><![CDATA[automated-testing]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Aditya Rohman]]></dc:creator>
            <pubDate>Wed, 26 Jan 2022 06:40:49 GMT</pubDate>
            <atom:updated>2022-02-07T07:40:42.331Z</atom:updated>
            <content:encoded><![CDATA[<h4>Menganal jenis pengujian yang umum diterapkan pada Flutter seperti unit testing, widget testing, dan integration testing.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CtNd3y-_ioDZr4i-X5fsZA.png" /><figcaption>Photo by <a href="https://unsplash.com/@girlwithredhat?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Girl with red hat</a> on <a href="https://unsplash.com/s/photos/testing?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p><em>Testing</em> atau pengujian adalah hal yang penting ketika mengembangkan sebuah produk berupa aplikasi. Dengan menerapkan <em>testing</em>, kita menjadi lebih percaya diri ketika akan merilis produk atau aplikasi tersebut ke publik karena kita sebagai developer dapat memastikan bahwa aplikasi yang kita kembangkan berjalan dengan baik sesuai yang diharapkan dan memiliki sedikit <em>bugs</em>.</p><h3>Jenis-Jenis Testing</h3><p>Metode <em>testing</em> yang umum diimplementasikan pada sebuah aplikasi ada 3 jenis, yaitu:</p><h4>Unit Testing</h4><p><em>Unit testing</em> merupakan jenis <em>testing</em> pada sebuah aplikasi dimana pengujian difokuskan kepada apa yang disebut dengan <em>unit</em>. <strong><em>Unit</em></strong> merupakan bagian terkecil yang membangun sebuah aplikasi. Contoh paling sederhana dari <em>unit</em> ketika kita berbicara tentang <strong><em>OOP (Object-Oriented Programming)</em></strong> adalah <strong><em>Class</em></strong> dan <strong><em>Function</em></strong>. <em>Unit testing</em> akan memastikan komponen-komponen kecil dari sebuah aplikasi berjalan dengan baik dan sesuai dengan ekspektasi.</p><p>Untuk melakukan <em>unit testing</em> kita menggunakan fungsi berikut:</p><pre>test(&#39;description&#39;, () {});</pre><p><strong>Contoh implementasi:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c6230780d5b3e0dbc133ab99af16c61/href">https://medium.com/media/3c6230780d5b3e0dbc133ab99af16c61/href</a></iframe><p>Pada kode di atas, kita coba melakukan <em>testing</em> untuk sebuah <em>unit</em> yaitu <em>datasource</em> movie_remote_data_source.dart untuk mendapatkan data <em>movies</em> dari <em>API</em>. Ada dua skenario yaitu (1) ketika data dari <em>API</em> berhasil didapatkan dan (2) ketika data dari <em>API</em> gagal didapatkan.</p><p>Satu blok kode <em>testing</em> secara garis besar terdiri dari 3 bagian yaitu:</p><ul><li><strong><em>Arrange</em></strong>: yaitu tahap dimana kita menyiapkan objek atau konfigurasi untuk <em>testing</em> (variabel dan nilai-nilai untuk testing). Pada contoh di atas, kita menyiapkan objek <strong><em>mock</em></strong> <strong><em>HTTP Client</em></strong> untuk dapat melakukan simulasi <em>request</em> data dari <em>API</em> saat <em>testing</em>.</li></ul><blockquote><strong>Mocking</strong> adalah membuat <strong>objek tiruan</strong> agar dapat digunakan untuk testing tanpa harus memikirkan ketergantungan (dependency) objek tersebut dengan objek lain dalam project.</blockquote><p><em>Library</em> yang digunakan untuk <em>mocking</em>:</p><ul><li><a href="https://pub.dev/packages/mockito">mockito | Dart package</a></li><li><a href="https://pub.dev/packages/mocktail">mocktail | Dart package</a></li></ul><ul><li><strong><em>Act</em></strong>: yaitu tahap dimana kita memanggil fungsi yang ingin diuji. Pada contoh di atas, kita memanggil fungsi getNowPlayingMovies() yang terdapat pada <em>class</em> MovieRemoteDataSourceImpl.</li><li><strong><em>Assert</em></strong>: yaitu tahap dimana kita memvalidasi aksi yang telah dijalankan apakah sudah sesuai dengan yang diekspektasikan atau tidak. Pada contoh di atas, ketika data berhasil didapatkan dari <em>API</em> kita memvalidasi hasil dari pemanggilan fungasi getNowPlayingMovies() apakah sama dengan tMovieList.</li></ul><h4>Widget Testing</h4><p><em>Widget testing</em> atau dalam istilah lain disebut dengan <strong><em>instrumentation testing</em></strong> merupakan jenis <em>testing</em> yang difokuskan kepada bagian-bagian yang membangun tampilan (<em>User Interface</em>) dari sebuah aplikasi seperti <em>button</em>, <em>text field</em>, dan sebagainya. <em>Widget testing</em> akan memastikan <em>User Interface</em> ditata sesuai dengan <em>UI design</em> aplikasi dan dapat berinteraksi baik dengan pengguna.</p><p>Untuk melakukan <em>widget testing</em> kita menggunakan fungsi berikut:</p><pre>testWidgets(&#39;description&#39;, (WidgetTester tester) {});</pre><p><strong>Contoh implementasi:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/13d64d350534e1da18ca555cb32f69ee/href">https://medium.com/media/13d64d350534e1da18ca555cb32f69ee/href</a></iframe><p>Proses yang dilakukan pada <strong><em>widget testing</em></strong> masih sama dengan <em>unit testing </em>yaitu <strong><em>arrange</em></strong>, <strong><em>act</em></strong>, dan <strong><em>assert</em></strong>. Perbedaannya adalah di sini kita menguji bagian dari tampilan (<em>User Interface</em>) aplikasi. Pada contoh di atas, kita menguji apakah ketika pengguna menambahkan <em>movie</em> ke <em>watchlist</em> dengan menekan tombol <strong><em>save watchlist</em></strong> maka sebuah SnackBar akan muncul.</p><p>Ketika tampilan atau <em>UI</em> aplikasi menerapkan <em>state management</em> seperti <em>provider</em>, <em>BLoC</em>, dan lainnya kita perlu mendeklarasikannya juga saat proses <strong><em>pump widget</em></strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c6675dec8ef9ac400afd6015fd229ab4/href">https://medium.com/media/c6675dec8ef9ac400afd6015fd229ab4/href</a></iframe><h4>Integration Testing</h4><p><em>Integration testing</em> merupakan jenis <em>testing</em> yang difokuskan untuk <strong>menguji keseluruhan jalannya aplikasi</strong> (<em>end-to-end testing</em>). Jadi, <em>integration testing</em> seperti gabungan dari widget testing. Untuk menjalankan <em>integration testing</em> dibutuhkan sebuah <em>emulator</em> atau <em>real device</em>. Saat pengujian berlangsung aplikasi akan tampil pada <em>emulator</em> atau <em>real device</em> dan menjalankan aplikasi secara otomatis.</p><p><em>Integration testing</em> sangat membantu untuk menguji bagaimana jalannya sebuah fitur atau seluruh aplikasi saat proses pengembangan. Akan lebih efisien dibandingkan kita harus menjalankan aplikasi dan menguji fitur atau seluruh aplikasi secara manual.</p><p>Untuk menerapkan <em>integration testing</em>, kita perlu menambahkan <em>library</em> pada pubspec.yaml.</p><pre>dev_dependencies:    <br>    ...<br>    <strong>integration_test:       <br>        sdk: flutter</strong></pre><p>Kemudian pada direktori <em>project</em>, kita perlu membuat sebuah folder baru bernama integration_test. Contohnya seperti berikut:</p><pre><strong>integration_test</strong><br>├── app_test.dart<br>└── robots<br>    ├── home_robot.dart<br>    └── ...</pre><p>Pada folder tersebut terdapat app_test.dart yang berisi semua skenario <em>end-to-end testing</em> untuk aplikasi kita. Kemudian ada juga folder robots yang berisi masing-masing skenario <em>testing</em>. Skenario <em>testing</em> aplikasi dapat dipisahkan (misalnya berdasarkan <em>page</em>).</p><p><strong>Contoh implementasi:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3956bbcaf7f813ecca6c300182cc0a67/href">https://medium.com/media/3956bbcaf7f813ecca6c300182cc0a67/href</a></iframe><p>Pada home_robot.dart di atas, kita membuat skenario <em>testing</em> yang ingin diuji pada <em>home page</em> dari aplikasi. Contohnya adalah membuka <em>drawer</em> ketika menekan tombol menu<em> </em>pada AppBar.</p><p>Untuk dapat mengakses <em>widget</em> yang kita tuju, kita dapat menggunakan Key(). Jadi kita harus mendaftarkan sebuah key pada <em>widget</em> yang ingin di-<em>testing</em>. Contohnya seperti berikut:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a809c2be6c00b7093293306bb4b71605/href">https://medium.com/media/a809c2be6c00b7093293306bb4b71605/href</a></iframe><p>Kemudian kita dapat menggabungkan semua skenario <em>testing</em> ke dalam app_test.dart.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d8a900d7cade9bc407d05b167b636756/href">https://medium.com/media/d8a900d7cade9bc407d05b167b636756/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d8a900d7cade9bc407d05b167b636756/href">https://medium.com/media/d8a900d7cade9bc407d05b167b636756/href</a></iframe><p>Sebelum bisa menjalankan <em>integration testing</em>, kita harus memastikan dulu apakah halaman aplikasi sudah muncul dan siap menerima input dengan memanggil fungsi berikut:</p><pre>IntegrationTestWidgetsFlutterBinding.ensureInitialized();</pre><p>Untuk menjalankan <em>integration testing</em>, siapkan <em>emulator</em> atau <em>real device</em>. Setelah itu, jalankan <em>command</em> berikut melalui <em>terminal</em>:</p><pre>flutter test integration_test</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*K3sstq48ruOaVB5W2zqMiQ.gif" /><figcaption>Hasil Integration Testing</figcaption></figure><h3>Kesimpulan</h3><p>Ketika mengembangkan aplikasi sebisa mungkin mempertimbangkan untuk melakukan <em>testing</em>. Agar hasil akhir aplikasi dapat terukur dengan baik dan memudahkan pemeliharaan ketika ada fitur yang ingin di-<em>revamp</em> atau <em>fixing</em>. Berikut adalah perbandingan ketiga jenis <em>testing</em> yang sudah dibahas:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/66243a66bfce6d62874203b222f55e2a/href">https://medium.com/media/66243a66bfce6d62874203b222f55e2a/href</a></iframe><p>Berikut adalah link untuk <em>full-code</em> project ini:</p><p><a href="https://github.com/codestronautHub/flutter-movie-database-app">GitHub - codestronautHub/flutter-movie-database-app: This is a movie catalog app. The main feature is movies dan tv shows list, watchlists, and many more. This app is powered by TMDB (The Movie DB)</a></p><p>Jadi itu sedikit pembahasan tentang <em>testing</em> pada <em>project</em> aplikasi <em>Flutter</em>. Semoga bermanfaat dan terimakasih! 🙌</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=71b6859b4cd4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tingkatkan Kualitas Aplikasi Flutter dengan Menerapkan Proses Test-Driven Development (TDD) dan…]]></title>
            <link>https://aditya-rohman.medium.com/mengembangkan-aplikasi-flutter-dengan-proses-test-driven-development-tdd-dan-mengadopsi-clean-29d29bb0702b?source=rss-8f67b6db7256------2</link>
            <guid isPermaLink="false">https://medium.com/p/29d29bb0702b</guid>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[tdd]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Aditya Rohman]]></dc:creator>
            <pubDate>Mon, 24 Jan 2022 16:10:17 GMT</pubDate>
            <atom:updated>2022-02-07T07:18:46.888Z</atom:updated>
            <content:encoded><![CDATA[<h3>Tingkatkan Kualitas Aplikasi Flutter dengan Menerapkan Proses Test-Driven Development (TDD) dan Mengadopsi Clean Architecture</h3><h4>Konsep detail dan implementasi TDD dan Clean Architecture pada Flutter</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F6z9QyNIn15-RBQN5uaIPA.png" /><figcaption>Photo by <a href="https://unsplash.com/@tricell1991?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Waranont (Joe)</a> on <a href="https://unsplash.com/s/photos/architecture-design?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Sejak dirilis ke publik pada 4 Desember 2018, ekosistem pengembangan aplikasi dengan <strong><em>Flutter</em></strong> sudah mengalami perkembangan yang sangat pesat. Memilih <em>Flutter</em> sebagai <em>SDK</em> untuk mengembangkan produk dengan iterasi yang cepat adalah pilihan yang tepat. Namun, bagaimana pun ketika memilih <em>Flutter</em>, <em>developer</em> juga harus mulai memikirkan <strong><em>state management</em></strong> pada aplikasi dan bagaimana merancang aplikasi (di balik layar) agar <strong>mudah diperihara</strong> dan <strong><em>scalable</em></strong>.</p><p>Untuk menjawab keresahan tersebut, kita perlu merancang arsitektur aplikasi sebelum mulai mengembangkan fitur.</p><h3>Clean Architecture</h3><p>Arsitektur adalah hal yang penting dalam pengembangan sebuah aplikasi. Arsitektur dapat diibaratkan seperti sebuah denah yang menggambarkan bagaimana alur dalam sebuah <em>project</em> aplikasi. Fungsi dari menerapkan arsitektur yang paling dasar adalah <strong><em>separation of concern</em> <em>(SoC)</em></strong>. Jadi, akan lebih mudah jika kita dapat bekerja dengan fokus pada satu hal dalam satu waktu.</p><p>Dalam konteks <em>Flutter</em>, <strong><em>clean architecture</em></strong> akan membantu kita untuk memisahkan kode untuk <strong><em>business-logic</em></strong> dengan kode yang berhubungan dengan <em>platform</em> seperti <strong><em>UI</em></strong>, <strong>s<em>tate management</em></strong>, dan <strong>sumber data eksternal</strong>. Selain itu, kode yang kita tulis pun dapat lebih mudah untuk diuji (<em>testable</em>) secara independen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KtSvmSz5XOeSTeBWEjUeXg.png" /><figcaption>Diagram Clean Architecture</figcaption></figure><p>Seperti pada diagram di atas, <strong><em>clean architecture</em></strong> digambarkan seperti sebuah piramida atau irisan bawang jika dilihat dari sisi atas. <em>Clean architecture</em> membagi <em>project</em> ke dalam <strong>3 lapisan (<em>layer</em>)</strong> yaitu:</p><h4>Lapisan data &amp; <em>platform</em></h4><p>Lapisan data terletak pada lapisan paling luar. Lapisan ini terdiri dari kode sumber data seperti <em>Rest API</em>, <em>local</em> <em>database</em>, <em>Firebase</em>, atau sumber lainnnya. Juga kode platform yang membangun tampilan aplikasi (<em>widgets</em>).</p><h4>Lapisan presentation</h4><p>Lapisan presentasi terdiri dari kode yang menjembatani komunikasi antara data dengan tampilan aplikasi yang disebut <strong><em>repository</em></strong>. Pada lapisan ini juga kita dapat meletakkan kode untuk <em>state management</em> aplikasi seperti <em>provider</em>, <em>controller</em>, <em>BLoC</em>, dan lain sebagainya.</p><h4>Lapisan domain</h4><p>Lapisan domain adalah lapisan terdalam pada <em>clean architecture</em>. Pada lapisan ini terdapat kode untuk <em>business-logic</em> aplikasi seperti <strong><em>entities</em></strong> dan <strong><em>usecases</em></strong>.</p><p>Masing-masing lapisan bergantung (<em>depends</em>) pada lapisan lainnya. Anak panah pada diagram menunjukkan bagaimana hubungan antar lapisan. Lapisan paling luar akan bergantung pada lapisan bagian dalam dan seterusnya.</p><p>Lapisan yang tidak bergantung pada lapisan lain di sini hanya lapisan domain (independen) yang merupakan kode untuk <em>business-logic</em>. Dengan begitu, aplikasi lebih bisa beradaptasi dan dinamis. Misalnya kita ingin mengganti <em>state management</em> dari <em>provider</em> menjadi <em>BLoC</em>, maka proses migrasi tidak akan mengganggu <em>business-logic </em>yang sudah ada.</p><h3>Test-Driven Development</h3><p>Selain menerapkan <em>clean architecture</em>, untuk mengoptimalkan proses pengembangan dalam arti <strong>menghasilkan aplikasi yang minim <em>bugs</em></strong> dan <strong>mengurangi proses <em>debugging</em> dan <em>fixing</em> yang repetitif</strong>, kita harus menjalani proses <strong><em>testing</em></strong>.</p><p><em>Test-Driven Development</em> adalah sebuah proses pengembangan aplikasi dimana <strong><em>testing</em> yang mengatur jalannya pengembangan</strong>. Skenario kode <em>testing</em> akan ditulis terlebih dahulu sebelum membuat sebuah fitur pada aplikasi.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h4aHudsWKs3QyERchcNnBg.png" /><figcaption>Alur Kerja Test-Driven Development</figcaption></figure><p>Alur kerja dari proses pengembangan aplikasi dengan <em>TDD</em> seperti diagram diatas. Proses <em>TDD</em> adalah proses yang berulang.</p><h4>Step — 1: Menulis skenario <em>testing</em></h4><p>Pengembangan sebuah fitur dimulai dengan menulis skenario <em>testing</em> terlebih dahulu. Penulisan skenario <em>testing</em> biasanya mengikuti <strong><em>feature requirements</em></strong> pada sebuah dokumen <em>PRD</em> (untuk kasus di sebuah perusahaan). Pada skenario pengujian biasanya akan terdapat alur dari fitur yang dikembangkan seperti menentukan sumber data yang digunakan (misalnya <em>remote</em> atau <em>local</em>), memastikan data yang masuk dari <em>API</em> menghasilkan <em>model</em> yang sesuai, merancang alur <em>state</em> dari tampilan berdasarkan data yang masuk ke aplikasi, dan lain sebagainya. Pada saat pertama kali menulis skenario testing, kita pasti akan mendapatkan <strong><em>error</em></strong>. Hal tersebut normal karena kode fiturnya belum ada.</p><blockquote>Menulis skenario <em>testing</em> sebuah fitur dilakukan sebagai panduan dalam mengembangkan fitur (<em>actual-code</em>).</blockquote><h4>Step — 2: Menulis kode fitur untuk membuat kode testing berhasil</h4><p>Pada langkah ini, penulisan kode fitur yang sebenarnya dilakukan. Penulisan kode pada tahap ini tidak harus rapi dan optimal karena tujuan utama pada langkah ini adalah membuat kode <em>testing</em> yang sudah dibuat sebelumnya menjadi berhasil.</p><h4>Step — 3: Refactor</h4><p>Setelah kode <em>testing</em> berhasil dijalankan tanpa adanya <em>error</em>, sekarang saatnya untuk merapikan dan mengoptimalkan kode yang sudah ditulis baik itu kode <em>testing</em> maupun kode fitur.</p><p>Dengan proses <em>TDD</em>, hasil akhir yang akan didapat selain aplikasi yang minim <em>bugs, </em>juga kode aplikasi yang rapi dan optimal.</p><h3>Implementasi</h3><p>Sekarang, kita akan coba mengimplementasikan konsep <strong><em>Test-Driven Development</em></strong> dan <strong><em>clean architecture</em></strong> dengan sebuah <em>mini-project</em> yaitu aplikasi cuaca. Kali ini kita akan memanfaatkan <a href="https://openweathermap.org/api">OpenWeather API</a> sebagai sumber data dari aplikasi kita.</p><p>Struktur folder <em>project</em> ini adalah sebagai berikut:</p><pre>lib<br>├── data<br>│   ├── constants.dart<br>│   ├── datasources<br>│   │   └── remote_data_source.dart<br>│   ├── exception.dart<br>│   ├── failure.dart<br>│   ├── models<br>│   │   └── weather_model.dart<br>│   └── repositories<br>│       └── weather_repository_impl.dart<br>├── domain<br>│   ├── entities<br>│   │   └── weather.dart<br>│   ├── repositories<br>│   │   └── weather_repository.dart<br>│   └── usecases<br>│       └── get_current_weather.dart<br>├── injection.dart<br>├── main.dart<br>└── presentation<br>    ├── bloc<br>    │   ├── weather_bloc.dart<br>    │   ├── weather_event.dart<br>    │   └── weather_state.dart<br>    └── pages<br>        └── weather_page.dart</pre><pre>test<br>├── data<br>│   ├── datasources<br>│   │   └── remote_data_source_test.dart<br>│   ├── models<br>│   │   └── weather_model_test.dart<br>│   └── repositories<br>│       └── weather_repository_impl_test.dart<br>├── domain<br>│   └── usecases<br>│       └── get_current_weather_test.dart<br>├── helpers<br>│   ├── dummy_data<br>│   │   └── dummy_weather_response.json<br>│   ├── json_reader.dart<br>│   ├── test_helper.dart<br>│   └── test_helper.mocks.dart<br>└── presentation<br>    ├── bloc<br>    │   └── weather_bloc_test.dart<br>    └── pages<br>        └── weather_page_test.dart</pre><p>Jika kamu ingin mengikuti tutorial ini, kamu dapat menggunakan<strong><em> starter code</em></strong> di <em>github repository</em> berikut:</p><p><a href="https://github.com/codestronaut/flutter-weather-app-sample.git">GitHub - codestronaut/flutter-weather-app-sample: This repository is a sample app for learning TDD and clean architecture in action!</a></p><h4>Step — 1: Membuat kode pada lapisan domain</h4><p>Langkah pertama adalah membuat kode pada lapisan <em>domain</em>. Kenapa lapisan <em>domain</em>? karena lapisan ini adalah lapisan yang tidak bergantung kepada lapisan apapun. Jadi akan lebih aman jika dimulai dari lapisan ini.</p><h4>Menulis kode <em>testing dan fitur usecase</em></h4><p>Pada bagian <em>test/domain</em>, kita hanya perlu menuliskan skenario <em>testing</em> untuk <em>usecases</em>. Pada kasus ini kita memiliki 1 buah <em>usecase</em> yaitu get_current_weather_test.dart.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9517a2b314d5b707c17ba19d0000a05a/href">https://medium.com/media/9517a2b314d5b707c17ba19d0000a05a/href</a></iframe><blockquote>Kode <em>testing usecase</em> diatas akan <strong><em>error</em></strong> diawal. Hal tersebut normal karena kita belum menulis kode fiturnya.</blockquote><p>Untuk kode fitur pada lapisan <em>domain</em>, terdapat 3 bagian yaitu <strong><em>entities</em></strong>, <strong><em>usecases</em></strong>, dan <strong><em>repositories</em></strong>. Kita mulai dengan menulis <em>weather entity</em> yaitu weather.dart.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2512411783c608b3f29d72fad7c62453/href">https://medium.com/media/2512411783c608b3f29d72fad7c62453/href</a></iframe><p>Setelah itu dilanjutkan dengan membuat kode untuk weather_repository.dart. Weather repository merupakan sebuah <strong><em>abstract class</em></strong> dan akan diimplementasikan nanti pada lapisan data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/073871528d35bacd35934b6f2f665f11/href">https://medium.com/media/073871528d35bacd35934b6f2f665f11/href</a></iframe><p>Kemudian, kita akan membuat kode untuk <em>usecase</em> get_current_weather.dart.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b2675877a53c665383801e711d505e63/href">https://medium.com/media/b2675877a53c665383801e711d505e63/href</a></iframe><p>Sebelum kembali ke kode <em>testing</em>, kita harus membuat <strong><em>mock weather repository</em></strong>. Buka test_helper.dart lalu tambahkan WeatherRepository. Pada test_helper.dart terdapat juga <em>mock</em> untuk <em>library </em><strong><em>HTTP</em></strong> agar dapat melakukan <strong>simulasi <em>request</em></strong> ke <strong><em>API</em></strong> pada saat <em>testing</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aa207b2d55dc206f48bb9949db342d8b/href">https://medium.com/media/aa207b2d55dc206f48bb9949db342d8b/href</a></iframe><p>Jalankan<em> command</em> berikut melalui terminal untuk menghasilkan <em>mock file</em><strong><em>:</em></strong></p><pre>flutter pub run build_runner build</pre><p>Setelah itu, kembali ke kode get_current_weather.dart dan <em>import</em> MockWeatherRepository lalu jalankan <em>testing</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/436/1*PxWrNkD1FrTh0Nq6UDX07w.png" /><figcaption>Hasil testing GetCurrentWeather usecase</figcaption></figure><h4>Step — 2: Membuat kode pada lapisan data</h4><p>Setelah mengerjakan kode <em>testing</em> dan fitur pada lapisan <em>domain</em>, sekarang kita lanjut untuk mengerjakan kode pada lapisan data. Pada lapisan data, terdapat <strong><em>data souces</em></strong>, <strong><em>models</em></strong>, dan <strong><em>repository</em></strong>.</p><blockquote>Sebentar, di lapisan <strong>domain</strong> juga ada repository? Iya, repository pada lapisan domain berbentuk <strong>abstract class </strong>yang didalamnya terdapat fungsi-fugsi yang masih harus perlu diimplementasikan. Nah, di repository pada lapisan <strong>data</strong> lah kita akan mulai mengimplementasikan abstract class tersebut.</blockquote><h4>Menulis kode testing dan fitur models</h4><p>Oke, kita akan mulai dari <em>models</em>, proses diawali dengan menulis kode <em>testing</em> untuk <em>model</em> yaitu weather_model_test.dart. Di sini, kita akan menguji 3 hal yaitu:</p><ul><li>Apakah <strong><em>model</em></strong> yang kita buat sudah sesuai dengan <strong><em>entity</em></strong> pada lapisan <em>domain</em>?</li><li>Apakah fungsi fromJson() mengembalikan <em>model</em> yang valid?</li><li>Apakah fungsi toJson() mengembalikan <em>JSON</em> <em>map</em> yang sesuai?</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dde29ede64edbae39a5eb858b230cce3/href">https://medium.com/media/dde29ede64edbae39a5eb858b230cce3/href</a></iframe><p>Kemudian, kita lanjutkan dengan menulis kode untuk weather_model.dart.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d356305cf83de0cf600322e4fb6b5ec3/href">https://medium.com/media/d356305cf83de0cf600322e4fb6b5ec3/href</a></iframe><p>Setelah itu, kembali lagi ke kode <em>testing</em>, <em>import</em> weather_model.dart lalu jalankan <em>testing</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*Hc3uwPi-lfi-cR25IlQNAA.png" /><figcaption>Hasil testing weather model</figcaption></figure><h4>Menulis kode testing dan fitur data sources</h4><p>Kita lanjutkan dengan mengerjakan kode pada <em>data sources</em>. Berikut adalah kode untuk remote_data_source_test.dart.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7abe3f10526e95dea0b9e453b731c1ed/href">https://medium.com/media/7abe3f10526e95dea0b9e453b731c1ed/href</a></iframe><p>Kode remote_data_source_test.dart di atas akan menguji proses mendapatkan data cuaca dari <em>API. </em>Ada <strong>dua kondisi</strong> di sini yaitu (1) mengembalikan <strong><em>model</em></strong> yang <em>valid</em> ketika membaca data berhasil, dan (2) mengembalikan <strong><em>exception</em></strong> ketika membaca data gagal. Kita juga membutuhkan <strong><em>dummy data</em></strong> dalam bentuk <em>JSON</em> seperti ini:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bd5b874d2c5d75f2af5938eef854a72f/href">https://medium.com/media/bd5b874d2c5d75f2af5938eef854a72f/href</a></iframe><p>Kemudian lanjut dengan menuliskan kode untuk <em>data source</em> yaitu remote_data_source.dart.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/49ceb40f711c269ee0086231529e4ea4/href">https://medium.com/media/49ceb40f711c269ee0086231529e4ea4/href</a></iframe><p>Setelah itu, kembali lagi ke kode <em>testing dan import</em> remote_data_source.dart lalu jalankan <em>testing</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/1*ftskEDnXk0CacBvx9lSFTQ.png" /><figcaption>Hasil testing remote data source</figcaption></figure><h4>Menulis kode testing dan fitur repository</h4><p>Selanjutnya, kita akan mengerjakan kode untuk <em>repository</em> yaitu weather_repository_impl_test.dart dan weather_repository_impl.dart. Istilah impl di sini berarti <em>implementation</em>.</p><p>Untuk testing pada weather_repository_impl_test.dart kita butuh untuk mengakses data source. Jadi, kita akan membuat <em>mock</em> dari RemoteDataSource yang sudah kita buat sebelumnya. Tambahkan RemoteDataSource pada test_helper.dart seperti berikut:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c1edab9efb0dbfb4d5500637527d7b3a/href">https://medium.com/media/c1edab9efb0dbfb4d5500637527d7b3a/href</a></iframe><p>Kemudian, jalankan <em>command</em> berikut untuk menghasilkan <em>mock file</em>:</p><pre>flutter pub run build_runner build</pre><p>MockRemoteDataSource<strong> </strong>udah siap digunakan. Sekarang kita akan mengerjakan kode untuk weather_repository_impl_test.dart.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/35e1a5f4d91119930a9d39859bf87a41/href">https://medium.com/media/35e1a5f4d91119930a9d39859bf87a41/href</a></iframe><p>Pada kode diatas skenario yang diuji adalah:</p><ul><li>Mengembalikan <em>current weather data</em> saat <em>request</em> ke <em>API</em> sukses</li><li>Mengembalikan ServerFailure saat <em>request</em> ke <em>API</em> gagal</li><li>Mengembalikan ConnectionFailure saat tidak terkoneksi ke internet</li></ul><p>Sekarang itu kita lanjut dengan mengerjakan weather_repository_impl.dart.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0f52eebd4365c78755159f86b67e9b76/href">https://medium.com/media/0f52eebd4365c78755159f86b67e9b76/href</a></iframe><p>Setelah itu, kembali lagi ke kode <em>testing dan import</em> weather_repository_impl.dart lalu jalankan <em>testing</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/1*d9DgvZapSwESLL9_97QGOg.png" /><figcaption>Hasil testing weather repository impl</figcaption></figure><h4>Step — 3: Membuat kode pada lapisan presentation</h4><p>Setelah mengerjakan pada lapisan <em>domain </em>dan<em> data</em>, langkah terakhir adalah mengerjakan kode pada lapisan <em>presentation</em>. Pada lapisan ini, terdapat <strong><em>state management</em></strong> (pada kasus ini kita menggunakan <em>BLoC</em>), dan <strong><em>pages</em></strong>.</p><h4>Menulis kode testing dan fitur BLoC</h4><p>Pertama, kita akan membuat kode <em>state management</em> <em>(BLoC)</em>. Untuk testing pada weather_bloc_test.dart, kita butuh untuk mengakses <em>usecase</em> yaitu GetCurrentWeather.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a85b0246a869807a9d2c34d832a32a43/href">https://medium.com/media/a85b0246a869807a9d2c34d832a32a43/href</a></iframe><p>Selanjutnya jalankan <em>command</em> berikut untuk menghasilkan <em>mock file</em>:</p><pre>flutter pub run build_runner build</pre><p>Kemudian, kita lanjut dengan mengerjakan kode <em>state management BLoC</em>. Di sini kode <em>BLoC</em> kita terdiri dari weather_state.dart, weather_event.dart, dan weather_bloc.dart.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e39e8441440be59a2dbae7ba1f2f4e2c/href">https://medium.com/media/e39e8441440be59a2dbae7ba1f2f4e2c/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/183beb97e02b38d3facd781e1855bfd9/href">https://medium.com/media/183beb97e02b38d3facd781e1855bfd9/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e42354edf716533b919ae508b71ee6d0/href">https://medium.com/media/e42354edf716533b919ae508b71ee6d0/href</a></iframe><p>Setelah itu, kembali lagi ke kode <em>testing dan import</em> weather_bloc.dart lalu jalankan <em>testing</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*y-RlQAngXD0NMArXBU4wLA.png" /><figcaption>Hasil testing weather bloc</figcaption></figure><h4>Menulis kode testing dan fitur Pages</h4><p>Setelah mengerjakan kode <em>BLoC</em>, selanjutnya kita akan membuat kode untuk pages atau UI dari aplikasi. Kita mulai dulu dengan kode <em>testing</em> yaitu weather_page_test.dart. Pada pengujian ini kita akan menguji 3 hal yaitu:</p><ul><li>State dari aplikasi seharusnya berubah dari WeatherEmpty menjadi WeatherLoading ketika selesai memasukkan data ke <em>widget</em> TextField.</li><li>Menampilkan <em>progress indicator</em> saat state dari aplikasi adalah WeatherLoading.</li><li>Menampilkan <em>widget</em> yang berisi informasi cuaca saat state dari aplikasi adalah WeatherHasData.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/395ba899a7a4dc20dbee2e9b9613ee3b/href">https://medium.com/media/395ba899a7a4dc20dbee2e9b9613ee3b/href</a></iframe><p>Kemudian, kita lanjutkan dengan membuat kode untuk weather_page.dart.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc73a2015a858378bf28f5f98752d874/href">https://medium.com/media/fc73a2015a858378bf28f5f98752d874/href</a></iframe><p>Setelah itu, kembali lagi ke kode <em>testing dan import</em> weather_page.dart lalu jalankan <em>testing</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*utdrMjv3A4pSLdSK98nhjQ.png" /><figcaption>Hasil testing weather page</figcaption></figure><h3>Menjalankan Aplikasi</h3><p>Sampai di sini, kita sudah menyelesaikan aplikasi dengan satu fitur yaitu mendapatkan informasi cuaca terkini berdasarkan pencarian nama kota. Sekarang, kita akan coba jalankan aplikasi pada emulator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zM7NGM35d3xwbszZR-AN2Q.png" /><figcaption>Hasil akhir</figcaption></figure><h3>Recap</h3><p>Proses penerapan <strong><em>Test-Driven Development</em></strong> dan <strong><em>clean architecture</em></strong> memang cukup kompleks. Tapi, jika kita berpatokan pada hasil akhir yaitu minim <em>bugs</em>, kemudahan dalam menambah fitur, dan migrasi <em>library</em> (seperti <em>state management</em>), <strong><em>it’s worth</em></strong>!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FwijMRo7UZXSqA%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FwijMRo7UZXSqA%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FwijMRo7UZXSqA%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/748c6efbc63e788b22bd96988fc9768f/href">https://medium.com/media/748c6efbc63e788b22bd96988fc9768f/href</a></iframe><p>Terakhir, kita dapat menjalankan test-coverage untuk mengetahui apakah semua kode sudah dilakukan testing. Jalankan command berikut pada direktori project di terminal:</p><pre>flutter test --coverage<br>genhtml coverage/lcov.info -o coverage/html<br>open coverage/html/index.html</pre><p>Hasilnya adalah:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b5cNvee6APIJ8EYFo1KdJg.png" /><figcaption>Hasil test-coverage</figcaption></figure><p>Jadi, itu dia proses penerapan <em>clean architecture</em> dan <em>TDD</em> pada <em>project</em> <em>Flutter</em>. Semoga bermanfaat. Terimakasih! 😊</p><p>Complete code dapat dilihat di sini:</p><p><a href="https://github.com/codestronaut/flutter-weather-app-sample.git">GitHub - codestronaut/flutter-weather-app-sample: This repository is a sample app for learning TDD and clean architecture in action!</a></p><p>Referensi:</p><ul><li><a href="https://ieeexplore.ieee.org/abstract/document/9071367">https://ieeexplore.ieee.org/abstract/document/9071367</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29d29bb0702b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>