<?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 Vaygeth (Abdulmohsen) on Medium]]></title>
        <description><![CDATA[Stories by Vaygeth (Abdulmohsen) on Medium]]></description>
        <link>https://medium.com/@vaygeth?source=rss-37cce710294------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*p_r1-XeCo7mwWg9Zu5aMTw@2x.jpeg</url>
            <title>Stories by Vaygeth (Abdulmohsen) on Medium</title>
            <link>https://medium.com/@vaygeth?source=rss-37cce710294------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 23:46:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vaygeth/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[Blazor Simplified: BLoC State Management For Blazor -  Part-1]]></title>
            <link>https://vaygeth.medium.com/blazor-simplified-bloc-state-management-for-blazor-part-1-9932291c3c4d?source=rss-37cce710294------2</link>
            <guid isPermaLink="false">https://medium.com/p/9932291c3c4d</guid>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[bloc]]></category>
            <category><![CDATA[blazor]]></category>
            <dc:creator><![CDATA[Vaygeth (Abdulmohsen)]]></dc:creator>
            <pubDate>Sat, 29 Jul 2023 09:46:42 GMT</pubDate>
            <atom:updated>2023-07-29T09:46:42.390Z</atom:updated>
            <content:encoded><![CDATA[<h2>Blazor Simplified: BLoC State Management For Blazor - Part-1</h2><p>In this series, I attempt to display the current challenges I faced in developing large-scale applications using Blazor and the approach I took to overcome these challenges.</p><h3>Blazor Current Challenges</h3><p>Blazor, Microsoft’s groundbreaking tool for creating interactive client-side web applications using .NET, has gained considerable attention in the web development community. However, like any technology, Blazor also comes with its own set of challenges:</p><ol><li>Passing States Between Many Components</li><li>Handling States Changes</li><li>Lack of Simplified State Management Packages (as of now)</li><li>Lack of Clear Design Pattern</li></ol><h3>Passing States Between Many Components</h3><p>As your projects grows, your passing data techniques manually isn’t convenient as you divide your components into a tree of nested components that share the same data. Normally we would pass data either as:</p><ul><li>[Parameter]</li><li>[CascadingParameter]</li><li>EventCallback&lt;T&gt;</li></ul><p>These approaches are good for few layers of components nesting for especially if your Data object that being passed not required to reactive to many Data State changes operations.</p><h3>Handling States Changes</h3><p>Due to its component-based architecture, a change in one component’s state may need to be reflected in other components. This can lead to problems with data synchronization and consistency, especially in large-scale applications with complex data interactions. In addition, you should have control of when/how to notify the other components of these data changes and decide manually when you want to rebuild the relying components.</p><h3>Lack of Matured State Management Packages</h3><p>In my opinion, I didn’t find a suitable state management package that simplifies the previous points without the implementation being complex or over-engineered solution (as of now).</p><h3>Lack of Clear Design Pattern</h3><p>Blazor is relatively new and as such, there aren’t yet universally accepted design patterns. This lack of clear design patterns can sometimes lead to disorganized and inefficient code.</p><h3>The Solution</h3><p>I published a package that aims to simplifies overcoming these challenges without major overhead in performance or boilerplate implementations.</p><p>As a developer coming from the Flutter development world, I personally use certain package for Flutter development that I like to use to tackle similar challenges that we have for Blazor, this package called <a href="https://pub.dev/packages/flutter_bloc">flutter_bloc</a>, which is a package that provide both a Design Pattern called Business Logic Component (BLoC) and a State Management solution. Shoutout to <a href="https://medium.com/u/bd78eebef416">Felix Angelov </a>for developing that package.</p><p>Inspired from that package, I converted it into a C# package that provide similar experience mainly based on the Cubit API available as <a href="https://www.nuget.org/packages/Vaygeth.Bloc.Blazor">Nuget package</a> and the source code on <a href="https://github.com/vaygeth89/Bloc.Blazor.Dotnet">github</a>.</p><p>Therefore in Part 2 of this series, I will explain and display on how to utilize this package to overcome the mentioned Blazor challenges. Stay tuned.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9932291c3c4d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Minimalist: App Account Management Part-2(not Firebase)]]></title>
            <link>https://vaygeth.medium.com/flutter-minimalist-app-account-management-part-2-not-firebase-c0232956161f?source=rss-37cce710294------2</link>
            <guid isPermaLink="false">https://medium.com/p/c0232956161f</guid>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[login]]></category>
            <category><![CDATA[firebase]]></category>
            <dc:creator><![CDATA[Vaygeth (Abdulmohsen)]]></dc:creator>
            <pubDate>Sun, 24 Oct 2021 10:53:44 GMT</pubDate>
            <atom:updated>2021-10-24T10:53:44.249Z</atom:updated>
            <content:encoded><![CDATA[<p>Implementing and calling HTTP Requests</p><h3>Intro</h3><p>This is Part 2 of the tutorial for Flutter account management where we demonstrated in <a href="https://vaygeth.medium.com/flutter-minimalist-app-account-management-not-firebase-76c2e7d764bb?source=user_profile---------0----------------------------">Part 1</a> how to set up our app to handle different user sign in states using a mocked API repository .</p><p>In this part, we will focus on replacing our mocked API repository with a real API repository that will make http requests with backend services.</p><h3>What you going to learn in this tutorial</h3><ol><li>Make use of http requests using <a href="https://pub.dev/packages/dio">dio package</a></li><li>Serialize dart classes/models into json using <a href="https://pub.dev/packages/json_serializable">json_serializable package</a></li></ol><h3>What not included in this tutorial</h3><ul><li>The backend/web-service code, the tutorial assumes you have a backend service that can meet our app requirements (sign-in, verifyToken, renewToken repositories)</li><li>If you want a tutorial on how to implement this in .NET (Core) contact me.</li></ul><p>Let’s get going…</p><h3>Dependencies</h3><p>First add the following dependencies that we need to fully complete this part</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/700e2a5d6ae1443c64be903acb3cb3a6/href">https://medium.com/media/700e2a5d6ae1443c64be903acb3cb3a6/href</a></iframe><p><a href="https://pub.dev/packages/dio">Dio</a></p><ul><li>The package that helps us make HTTP requests to our web-services</li></ul><p><a href="https://pub.dev/packages/json_serializable">Json_serializable</a></p><ul><li>The package that helps us convert our data models into json or vise versa by adding decorators/annotations into our model classes without doing this work manually</li></ul><p><a href="https://pub.dev/packages/build_runner">Build_runner </a>(as dev_dependencies)</p><ul><li>The package is a utility package that helps with many other packages to build its configuration, for example we will use it along with json_serializable to build the annotated data model classes and generate the files that has the code converting our model classes into json.</li></ul><h3>Generate Serialized Models</h3><p>Since we intend in this part to replace the mocked api repository in <a href="https://vaygeth.medium.com/flutter-minimalist-app-account-management-not-firebase-76c2e7d764bb?source=user_profile---------0----------------------------">Part 1</a>, and create a repository that makes real HTTP requests, then we need our models that will be sent/requested to the web-services to serialize into JSON objects or data that are returned/responded from the web-services to be deserialized back to our model classes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/253/0*TxCk3fwM97Zzv_gz" /></figure><p>So let’s make use of the <a href="https://pub.dev/packages/json_serializable">Json_serializable</a> package to help us to do so by adding annotation into our models and the necessary imports</p><h4>sign_in.dart</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e331cd30044627ebc80d8a09ccca556c/href">https://medium.com/media/e331cd30044627ebc80d8a09ccca556c/href</a></iframe><h4>renew_access_token.dart</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e30db93a9b4048597f39edfdc0d95fd1/href">https://medium.com/media/e30db93a9b4048597f39edfdc0d95fd1/href</a></iframe><h4>authentication_data.dart</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/045cdc44d70f65c117a3967f83695f1e/href">https://medium.com/media/045cdc44d70f65c117a3967f83695f1e/href</a></iframe><h4>business_error.dart</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4be03b397e0fd7061f4ec47353b3cab1/href">https://medium.com/media/4be03b397e0fd7061f4ec47353b3cab1/href</a></iframe><p>Then from the Terminal/CMD/Powershell run the following command to build and generate our auto created file for serialization</p><blockquote><strong>Flutter pub run build_runner build</strong></blockquote><p>Note if your classes contains errors (beside the toJson &amp; fromJson we added) the above command will not work. Also if you try to rebuild your models in the future by adding new properties or changed files you may want to run the command with the option <em>— delete-conlficting-ouputs</em> to replace old classes like so</p><blockquote><strong>Flutter pub run build_runner build — delete-conlficting-ouputs</strong></blockquote><h3>Result</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/282/0*uHMIJpFyhMAcQTzk" /></figure><p>Now our model classes are generated we can proceed with creating the account API repository that will make HTTP requests to our web-services.</p><h3>API Repository</h3><p>Create a file named account_api_repository.dart under lib/repositories/api/ folders (same level as account_repository.dart that was created in <a href="https://vaygeth.medium.com/flutter-minimalist-app-account-management-not-firebase-76c2e7d764bb?source=user_profile---------0----------------------------">Part 1</a>)</p><p>and define class named AccountApiRepository that implements AccountRepository abstract class and override the required methods, like so</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b860ee7cdc511984cc9b172059cd865b/href">https://medium.com/media/b860ee7cdc511984cc9b172059cd865b/href</a></iframe><p>Since we are going to make HTTP requests to our account web-services, we need to define our URL (Domain Name Server (DNS) or IP) of our web-service on the network, therefore base on where your web-services are you should input your URL and not my local IP since I’m testing this locally on my network (like using emulators)</p><p>So create a file named constants.dart under lib/constants/ and add our account service URL.</p><p>Note this assumes the account web-services have the same base URL root as I’m using like so</p><ul><li><a href="https://{myurl}/api/account/v1/sign-in">https://{myurl}/api/account/v1/sign-in</a></li><li><a href="https://{myurl}/api/account/v1/verify-token">https://{myurl}/api/account/v1/verify-token</a></li><li><a href="https://{myurl}/api/account/v1/renew-token">https://{myurl}/api/account/v1/renew-token</a></li></ul><p>So if your web-services have different base routes (for instance sign-in webservice is <a href="https://mydns/api/v1/auth/sign-in">https://mydns/api/v1/auth/sign-in</a> while verifyToken web-service lives in another URL like <a href="https://mydns/api/v1/verify/verify-token">https://mydns/api/v1/verify/verify-token</a> you may want to adjust or add several URLs in the constants files).</p><p>Nevertheless here’s how I’m defining it like so</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/78680748f7879c049ad521ed5159b933/href">https://medium.com/media/78680748f7879c049ad521ed5159b933/href</a></iframe><h3>Code reusability</h3><p>There’s an extra step (optional), to create an account api base class that can hold several properties that may be needed to complete for the most of the API classes (maybe you add new ones for different cases) that share common data, like HTTP headers, time-out durations and services base URLs.</p><p>This will help reduce our code redundancy and keep it DRY by our APIs repositories to extend it</p><p>So create an abstract class named ApiRepositoryBase in the same file as <em>AccountApiRepository </em>(or you can move it to a different file as you wish) that will contain</p><ul><li><em>Base URL</em>, since we are expecting any account related web services have the same base URL as described in constants.dart</li><li><em>Default Header</em> about content we expecting which is JSON data</li><li><em>Dio </em>object with the above data configured</li><li><em>Bearer header</em> (this will be helpful when used to access certain resources that require authorization)</li><li>Timeout property that notify when our requests expires (currently set to 8 seconds)</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8ddc6fdbd8fd4e84cb2c7b54416dfb80/href">https://medium.com/media/8ddc6fdbd8fd4e84cb2c7b54416dfb80/href</a></iframe><h3>AccountApiRepository Implementation</h3><p>We will make our class to extend the ApiRepositoryBase like so and pass our <em>accountAPIURL_v1 </em>URL we defined in constants.dart as our base URL and change our methods into async methods like so</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4c6146d55794fd2b00ca4c7975b64456/href">https://medium.com/media/4c6146d55794fd2b00ca4c7975b64456/href</a></iframe><p><strong>Methods implementations</strong></p><p><em>signIn()</em></p><ul><li>Add <em>routePath</em> into the method parameters if needed, mine is sign-in for the resource URL that expects an HTTP POSToperation for the sign-in web-service</li><li>POST SignIn data into the HTTP request using our super (ApiRepositoryBase dio object) and convert it into JSON</li><li>Set timeout for the HTTP request from the superclass timeout property (you can change this property to what duration you prefer)</li><li>Handle if the response was successful by checking the HTTP response status code (200)</li><li>Throw <em>DioError</em> exception if the HTTP response status code is not 200 passing it the result options that contains the error details</li><li>Catch the failed exception and throw the <em>BusinessException</em> by trying to parse the response data into the <em>BusinessError </em>class. Note if the Business Error parsing fails it will throw an exception which can be considered not a business error (i.e service is down, timeout…etc)</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f675a7ff12f7ec282ee0540c6ec15a5c/href">https://medium.com/media/f675a7ff12f7ec282ee0540c6ec15a5c/href</a></iframe><p><em>verifyToken()</em></p><ul><li>Add <em>routePath</em> into the method parameters if needed, mine is verify-token for the resource URL that expects an HTTP GET operation for the verify token web-service</li><li>Call the web-service using super.dio.get(), with the queryParameter containing our accessToken as follows</li><li>Handle if the response was successful by checking the HTTP response status code (200) and return true</li><li>Throw <em>DioError</em> exception if the HTTP response status code is not 200 passing it the result options that contains the error details</li><li>Catch and throw exception if the HTTP response status code is above 400 (by convention HTTP 4XX error codes) and throw <em>AccessTokenException </em>to handle it from <em>UserAuthenticationCubit</em> notify that the access token was invalid or expired</li><li>Catch and throw the failed exception was not HTTP status code 4XX and throw the <em>BusinessException</em> by trying to parse the response data into the <em>BusinessError </em>class like we handled in the <em>signIn()</em></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d139a99ee47db605fdb743d0ae322f4/href">https://medium.com/media/2d139a99ee47db605fdb743d0ae322f4/href</a></iframe><p><em>refreshToken()</em></p><ul><li>Add <em>routePath</em> into the method parameters if needed, mine is refreshToken for the resource URL that expects an HTTP GET operation for the verify token web-service</li><li>Call the web-service using super.dio.post(), with the refresh token data passed into the body and converted into JSON object</li><li>Handle if the response was successful by checking the HTTP response status code (200) and return the data from the web-service by deserializing it into AuthenticationData class</li><li>Throw <em>DioError</em> exception if the HTTP response status code is not 200 passing it the result options that contains the error details</li><li>Catch and throw exception if the HTTP response status code is above 400 (by convention HTTP 4XX error codes) and throw <em>RefreshTokenException </em>to handle it from <em>UserAuthenticationCubit</em> notify that the refresh token was invalid or expired</li><li>Catch and throw the failed exception was not HTTP status code 4XX and throw the <em>BusinessException</em> by trying to parse the response data into the <em>BusinessError </em>class like we handle it previously</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/47fb7a6995dbda19cf5dae3b46cbca4f/href">https://medium.com/media/47fb7a6995dbda19cf5dae3b46cbca4f/href</a></iframe><p>Here’s the full code for the <em>account_api_repository.dart </em>with further comments to guide you further</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e95f84173fb0125fccfbfdda75f9b741/href">https://medium.com/media/e95f84173fb0125fccfbfdda75f9b741/href</a></iframe><h3>main.dart</h3><p>Now the final part is go into our main.dart file and replace our FakeApiRepository() that is being passed to our UserAuthenticationCubit() that we created in <a href="https://vaygeth.medium.com/flutter-minimalist-app-account-management-not-firebase-76c2e7d764bb?source=user_profile---------0----------------------------">Part 1</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9a3f1ea1a7b472874d4686ec15c51c97/href">https://medium.com/media/9a3f1ea1a7b472874d4686ec15c51c97/href</a></iframe><p>This concludes Part 2 of the series, in the next parts of the series we will implement the user sign up feature like we did for the sign in part.</p><p>For the full source code <a href="https://github.com/vaygeth89/tutorial_flutter_minimalist_authentication/tree/part2">click here</a></p><p>Make sure to follow and clap, much appreciated</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c0232956161f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Minimalist: App Account Management Part 1 (not Firebase)]]></title>
            <link>https://vaygeth.medium.com/flutter-minimalist-app-account-management-not-firebase-76c2e7d764bb?source=rss-37cce710294------2</link>
            <guid isPermaLink="false">https://medium.com/p/76c2e7d764bb</guid>
            <category><![CDATA[login]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[auth]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Vaygeth (Abdulmohsen)]]></dc:creator>
            <pubDate>Sat, 16 Oct 2021 17:10:55 GMT</pubDate>
            <atom:updated>2021-10-24T10:57:01.093Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Part 1 Persistence User Authentication with Cubit</strong></p><p>This is part one of the series where we will implement user authentication that persists even when users close the app and handle additional cases when sessions expire and need to be renewed to reduce the number of users entering their credentials. The tutorials will be implemented in parts as follows:</p><ol><li>Part 1 — Implement User Authentication State with mocked API service (without making http request)</li><li>Part 2 — Implement Sign In API service to make Http requests and discard the mocked API that was implemented in Part1 (stay tuned by following)</li><li>Part 3 — Add User Sign Up feature with mocked service</li><li>Part 4- Implement Sign Up API service to make Http requests and discard the mocked API</li></ol><p><strong>What’s this tutorial about:</strong></p><p>1- Protect secured pages/screens/features that only sign in users to access</p><p>2- Implement Sign In Logic using OAuth2 or JWT session based authentication (AccessToken, RefreshToken…etc)</p><p>3- Dividing our project into several layered classes that handles it’s single responsibility (UI, States, Events,Services..etc as shown in the following figure)</p><p>4- Will implement our State management using Flutter Bloc specifically using Cubit states</p><p>5- Give our states a meaningful naming that describes different sign in conditions (like when invalid credentials, email not verified, invalid credentials…etc)</p><p><strong>The Project Requirements</strong></p><ul><li>Landing Page</li><li>Profile Page</li><li>Sign In Page</li></ul><p><strong>The Landing Page</strong></p><ul><li>Contains a button that takes logged in users to their profile page</li><li>Only Authenticated users can navigate to Profile page otherwise they will be redirected to Sign In Page</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qemEumi-sc9YYbRJ" /><figcaption>Figure 1</figcaption></figure><p><strong>The Profile Page</strong></p><ul><li>Is to show users private information, and is protected by preventing unauthenticated to access it</li><li>For simplicity we are going to show only User ID and access token</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*StnMW0Ziiik5VGHg" /><figcaption>Figure 2</figcaption></figure><p><strong>The Sign In Page</strong></p><ul><li>Where users are able to input their credentials and get authenticated</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/0*xQajDJaZhxNyRcYN" /><figcaption>Figure 3</figcaption></figure><p><strong>Project Design Pattern Overview</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*s_HhgalgiXdx8bxZ" /><figcaption>Figure 4</figcaption></figure><p><strong>Packages and prerequisites</strong></p><p>Before we begin, let’s add the required packages like shown in following image</p><ul><li><a href="https://pub.dev/packages/flutter_bloc">Flutter_Bloc</a> (Using Cubit state management)</li><li><a href="https://pub.dev/packages/flutter_secure_storage">Flutter_Secure_Storage</a> (To save private data securely on our phone, access token and refresh token)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/0*8LgsP2siFnNW25uP" /><figcaption>Figure 5</figcaption></figure><p>In order to store private information on the devices using flutter_secure_storage make sure we increase the minimum required Android SDK in Android build.grade as shown</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/0*ik6xtYdjzn5XrL88" /><figcaption>Figure 6</figcaption></figure><p><strong>App User Authentication Flow</strong></p><p>App Auth service is responsible for calling requests to our backend service/server APIs to inform our app that the user is authenticated state, or unauthenticated state (and other states)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*71i5eRMIK6XVG_2z" /><figcaption>Figure 7</figcaption></figure><p><strong>Coding Time</strong></p><p>For developing the project, I will mainly highlight the important pieces of the code and will not include all the details in upcoming implementation, however the full source code is available on <a href="https://github.com/vaygeth89/tutorial_flutter_minimalist_authentication">github repo</a> that you can reference.</p><p><strong>API/Repositories</strong></p><p>We will start implementing our mock up API class here since it doesn’t have any dependencies on other classes, and is the responsible class to request data from our backend (in part 1 we are creating a mockup for this class and part 2 of the tutorial we will implement the real API repository making Http Requests to our backend)</p><p>Create a file named <em>api_repository.dart</em> under <em>repository/api </em>folders as follows</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ac66d689a4bac2775c71a0a16c91a1b0/href">https://medium.com/media/ac66d689a4bac2775c71a0a16c91a1b0/href</a></iframe><p>API Repository Methods</p><p><strong>SignIn()</strong></p><ul><li>Responsible for authenticating the user</li></ul><p><strong>VerifyToken()</strong></p><ul><li>Will cross check the current Access Token in device still valid</li></ul><p><strong>RenewAccessToken()</strong></p><ul><li>Responsible to renew User Authentication data by having new Authentication data like Access Token</li></ul><p>Now API repositories need some classes that are not yet created in order to proceed with making http requests in the future, so let’s create them under <em>models/</em> folder</p><p><strong><em>sign_in.dart</em></strong> model</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f1a998df1d9ce86b39454190d1460e2/href">https://medium.com/media/4f1a998df1d9ce86b39454190d1460e2/href</a></iframe><p><strong><em>renew_access_token.dart</em></strong> model</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b173e2cedcb8187d803487df10b92e4/href">https://medium.com/media/7b173e2cedcb8187d803487df10b92e4/href</a></iframe><p><strong><em>authentication_data.dart</em></strong> model</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e38353f26576aa73ca32498243db697e/href">https://medium.com/media/e38353f26576aa73ca32498243db697e/href</a></iframe><p>Now implementing our concrete API Repository (in this part is a mock up class) so we are gonna name it FakeAPIRepository and implement the abstract APIRepository and override the required methods in a mock-up manner. Therefore we are gonna put static values for email,password, access &amp; refresh token and auth data.</p><p>Create <em>fake_account_api_repository.dart</em> under <em>repository/api/</em> folders</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/865a1816e939b207531eea9ce3b07105/href">https://medium.com/media/865a1816e939b207531eea9ce3b07105/href</a></iframe><p><strong>Bloc/Cubit State Management Classes</strong></p><p>Now this is the important parts where our States Management events and states are responsible pieces to orchestrate user Events like Sign In and communicate this to our API Repository to get authenticated, so let’s define and plan what are the possible User Authentication states</p><p><strong>States</strong></p><p><em>Is the end result/output of an event either triggered by the system or UI events like button tapping to sign in</em>.</p><p><strong><em>UserAuthenticationInitial</em></strong></p><ul><li>This states is emitted when the app is first opened and notify our app that it needs to try and validate our stored user authentication data (if they exist) like access token with our API Repo</li></ul><p><strong><em>UserAuthenticating</em></strong></p><ul><li>The defines the app is in authenticating states like waiting to server to confirm or reply whether the sign in is successful or not</li><li>Therefore we can use this state to show the users that the app is processing the data and show a loading indicator</li></ul><p><strong><em>UserAuthenticated</em></strong></p><ul><li>This when our API returns a successful Sign In and the user credentials were valid</li><li>The app is considered the user is authenticated and allow him to access pages/features that requires elevated privileges</li><li>This state will wrap our session data (AuthenticationData)</li></ul><p><strong><em>UserAuthenticationInvalidCredentials</em></strong></p><ul><li>This when our API returns a failed Sign In and the user credentials were invalid</li><li>We defined this State in order to show the user email &amp; password that he entered were incorrect</li></ul><p><strong><em>UserAuthenticationEmailNotConfirmed</em></strong></p><ul><li>This just an extra state that some developers want to handle, for example sometimes users Sign Up to an app/website and the service requires to verify the user email in order to Sign In successfully</li></ul><p><strong><em>UserAuthenticationError</em></strong></p><ul><li>The purpose of this state is to notify the app the authentication for some reason didn’t complete or return other generic errors, for example back API service is down, service timeout…etc</li></ul><p><strong><em>UserUnauthenticated</em></strong></p><ul><li>This state can be emitted for any handled exceptions,cases when app failed to authenticate with the service, for example when user first open the app and the app tried to fetch stored session data like access token from devices (means the user didn’t sign in before or forced delete the app data)</li></ul><p>Create a file named <em>user_authentication_state.dart</em> as follows under <em>cubit/ </em>folder</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8eab8cc52e3644655c1b4eb88858ec9f/href">https://medium.com/media/8eab8cc52e3644655c1b4eb88858ec9f/href</a></iframe><p><strong>Cubit</strong></p><p><em>Is the responsible class to coordinate both user events and system events in order to communicate with services and update the app state</em></p><p>Create a file named <em>user_authentication_cubit.dart</em> as follows under <em>cubit/</em> folder</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/42edfd1d833bf6d62716f272b4e589b3/href">https://medium.com/media/42edfd1d833bf6d62716f272b4e589b3/href</a></iframe><p>The <em>UserAuthenticationCubit </em>class contains different methods that however we will focus on the ones that will</p><p><strong>validateAuthentication()</strong></p><ul><li>There’s several nested conditions here, first the method tries to fetch existing stored Authentication info (access,refresh tokens and user id) stored on device secured storage</li><li>If there’s no stored Authentication Data then it will emit the <em>UserUnauthenticated </em>and is considered not logged-in.</li><li>If info are stored then it will make API call to our backend (in this case fake service) using AccountRepository.validateToken(accessToken) sending it the Access Token to verify its validity</li><li>If the service returns a successful response (for example Http 200) then the method emits and changes the state to UserAuthenticated (logged-in)</li><li>Else the service tries to renew the session by having a new Access Token by calling AccountService.renewAccessToken(refreshtoken)</li><li>If service returns successful Http status 200 then it will store or replace the existing Authentication Data with the new one into the device secure storage and emit/notify that the user is UserAuthenticated</li><li>Else if service is not successful (for whatever reason) the method will clear stored Authentication Data and emits <em>UserUnauthenticated </em>state</li><li>Notice by default, I usually fire &amp; call this method upon creating an instance of the <em>UserAuthenticationCubit </em>in order to validate the user info without waiting for it to finish, because are updating UI states reactively.</li><li>You can use this method whenever suitable, however I like to fire it upon instantiating the Cubit because it only happens once when the user opens the application</li></ul><p><strong>logoutUser()</strong></p><ul><li>This is a simple method that deletes all user stored data (access, refresh tokens and user id) and emits <em>UserUnauthenticated </em>state</li></ul><p><strong>signInUser(signInInput)</strong></p><ul><li>This is self explanatory method, this method will only be used when users input their credentials in the Sign In Page and click Login, however notice there’s several scenarios (States) that need to be considered and handled by our app UI to have further descriptive and informative error handling to show or redirect users to corrective behaviour according to the business requirements. For the simplicity of this tutorial, I’ve limited this to several following cases:</li><li>Users enter invalid credentials, this happens when our backend service returns Http Status 400 (Bad request) and returns an object (BusinessError.dart) in the response with containing error code 123</li><li>Then the event will emit <em>UserAuthenticationInvalidCredentials</em></li><li>Based on that error code, the state will be emitted, and our app will show error message notifying users that they entered invalid credentials</li><li>Users enters correct credentials but the business requires the user email to be verified in order to sign-in successfully (to receive tha Authentication Data), this happens when our backend service returns Http Status 400 (Bad request) and returns an object (BusinessError.dart) in the response with containing error code 321</li><li>Then the event will emit <em>UserAuthenticationEmailNotConfirmed</em></li><li>Based on that error code, the state will be emitted, and our app will show a message that they need to check their email in order to verify and confirm email connected to heir account</li><li>Users enter invalid/valid credentials but the operations failed for some reasons, for example</li></ul><ol><li>Mobile Internet went down</li><li>Server is not reachable (network, url no longer valid)</li><li>Network Timed Out</li><li>Other may other odd cases</li></ol><p>Based on the above, we can show a generic message like the service is not available at this time, and they need to try again later on.</p><p><strong>Time to Widget</strong></p><p>The overall strategy for our app, is to give good user experience where the app will allow different type of users to use the app in both guest users (unauthenticated) and logged-in (authenticated) users to access various parts of the application and only limit guest users for accessing certain features (widgets/pages). So in this tutorial we will give the following permissions as follows</p><p><strong>Guest Users</strong></p><ul><li>Allowed access to Landing Page</li><li>Allowed access to Sign In Page</li></ul><p><strong>Logged-in Users</strong></p><ul><li>Allowed access to Landing Page</li><li>Allowed access to Profile Page</li></ul><p>As per above, we notice the guest users can’t access Profile page (to view user info) and the logged-in users can’t access the Sign In page (naturally since they are already authenticated), therefore we can conclude that Profile page &amp; Sign In page are mutually exclusive (they can’t coexists or is accessible for the same user).</p><p>To achieve the above, we need to somehow protect and coordinate to make sure these features (Profile &amp; Sign In pages) should never overlap for the same user state (authenticated or unauthenticated)</p><p><strong>The solutions</strong></p><p>Is to wrap any feature that may require elevated access (authenticated) that coordinates based on the user’s current state and also reduce code redundancy (DRY i.e Don’t Repeat Yourself), and to do so I came up with a Wrapper Widget that wraps features/pages that we want to protect, so I named it <em>ProtectionWidget </em>that host the <em>UserAuthenticationCubit </em>&amp; <em>UserAuthenticationStates </em>and build the appropriate widget accordingly.</p><p>Here’s the High Level Flow</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dPmtuAU5eMxMbK5-" /><figcaption>Figure 8</figcaption></figure><p>Let’s code our routes first and add the pages afterward</p><p><strong>Routes Class</strong></p><p>This class simply defines the route names and maps to what page. Note for simplicity, I’m going to use navigator 1.0 without any plugins, where navigator 2.0 will be full of boilerplate code, so I suggest to use Flutter packages like to stay with the latest navigation version and make things easier and supports different platforms like named routes for Web platform when user manually enters the URL manually and navigate to a specific page.</p><p>Checkout the following packages</p><ul><li><a href="https://pub.dev/packages/get">Get package</a></li><li><a href="https://pub.dev/packages/velocity_x">Velocity X package</a></li></ul><p>Nevertheless, here’s our navigator 1.0 class. Create file named <em>routes.dar</em>t as follows under <em>routes/</em> folder</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/096cd2c6ecdbf320d2d6752acbe4a893/href">https://medium.com/media/096cd2c6ecdbf320d2d6752acbe4a893/href</a></iframe><p>Now we create the required pages/widget that Routes Class needs</p><p><strong>Landing Page</strong></p><p>Create landing_page.dart file as follows under <em>pages/</em> folder</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a1549b63cd0f62d60c67f953da4ab268/href">https://medium.com/media/a1549b63cd0f62d60c67f953da4ab268/href</a></iframe><p><strong>Profile Page</strong></p><p>Create profile_page.dart file as follows under <em>pages/</em> folder</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0013fd03d3ff2e4ba74f697b47b8f626/href">https://medium.com/media/0013fd03d3ff2e4ba74f697b47b8f626/href</a></iframe><p><strong>Sign In Page</strong></p><p>Create sign_in_page.dart file as follows under <em>pages/</em> folder</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e3a15a3e6576cc622c2fd0c47528c1f4/href">https://medium.com/media/e3a15a3e6576cc622c2fd0c47528c1f4/href</a></iframe><p><strong>Main Widget</strong></p><p>Now let’s hook up our app to be functional without any state aware logic in the main.dart</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aef6aff032ffca9afcf66cbf5e4074aa/href">https://medium.com/media/aef6aff032ffca9afcf66cbf5e4074aa/href</a></iframe><p>For now our app will be fully functional but is not state aware yet, so to</p><p><strong>Protection Widget</strong></p><p>Now the important bit of this tutorial that wire everything we wrote, is to create a widget that wraps the user authentication cubit and helps coordinate which UI should be built according to user authentication state.</p><p>Create a file named protected_widget.dart under a folder named widgets/</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6d8f11a62b751498bd5e2edc5717e02d/href">https://medium.com/media/6d8f11a62b751498bd5e2edc5717e02d/href</a></iframe><p>You will notice that the widget accepts 2 required parameters</p><p><strong>onAuthenticated builder widget</strong></p><ul><li>This builder widget is returned when the user is authenticated, along with user <em>AuthenticationData</em></li></ul><p><strong>onUnauthenticatedChild widge</strong>t</p><ul><li>This widget will be built when the user is not <em>UserAuthenticatedState</em>, that means any of the other states</li><li>In this tutorial we will only use it for showing the <em>SignInPage </em>widget</li><li>Note you can handle extra states and return your desired widget/behaviour like handling <em>UserAuthenticating </em>state and show progress bar</li></ul><p>Now let’s make our application be aware of user authentication states</p><p><strong>MyApp widget</strong></p><p>Wrap Material app with MultiBlocProvider in order to make the UserAuthentication state can be watched/read from any part of the widget tree</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3caa5382055a74f07505e6c7a9ad2a40/href">https://medium.com/media/3caa5382055a74f07505e6c7a9ad2a40/href</a></iframe><p><strong>SignInPage</strong></p><ul><li>Include the <em>UserAuthenticationCubit </em>in the widget in order to allow it to handle user sign in event when sign in button callback is invoked</li><li><em>SignInForm </em>also need to be aware of the different user authentication states especially the failed cases as follow <em>UserAuthenticationError</em>, <em>UserAuthenticationEmailNotConfirmed</em>, and <em>UserAuthenticationInvalidCredentials </em>in order to show the error message for the different cases</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4c33d1d11ab023d53a750717f50ef607/href">https://medium.com/media/4c33d1d11ab023d53a750717f50ef607/href</a></iframe><p><strong>ProfilePage</strong></p><p>Finally wrap our build method with the created ProtectedWidget as follows:</p><ul><li>Passing the SignInPage to <em>onUnauthenticatedChild </em>parameter</li><li>For <em>onAuthenticated </em>we keep the original profile widgets that was previously created along displaying some user authentication data that was returned from the builder like access token and user id</li><li>Finally include and watch <em>UserAuthenticationCubit </em>at the beginning of the build method and handle the logout event when user table the logout icon button, in order to sign-off the user and direct him to the <em>SignInPage</em></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/92b57cd9b2b8157a14f574d055687e87/href">https://medium.com/media/92b57cd9b2b8157a14f574d055687e87/href</a></iframe><p>This concludes part 1 of the series, in the next part we will replace the mocked and fake API with a real one to make http requests. Stay tuned and <strong>follow me</strong> to stay up today for coming parts</p><p>For the source control of this part <a href="https://github.com/vaygeth89/tutorial_flutter_minimalist_authentication">click here</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76c2e7d764bb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[.NET Core — Adding JWT Claims To Web API — Part 2 The APIs Implementation]]></title>
            <link>https://vaygeth.medium.com/net-core-adding-jwt-claims-to-web-api-part-2-the-apis-implementation-5b6c2ca6fe98?source=rss-37cce710294------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b6c2ca6fe98</guid>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Vaygeth (Abdulmohsen)]]></dc:creator>
            <pubDate>Wed, 18 Nov 2020 22:37:12 GMT</pubDate>
            <atom:updated>2020-11-18T22:37:12.174Z</atom:updated>
            <content:encoded><![CDATA[<h3>.NET Core — Adding JWT Claims To Web API — Part 2 The APIs Implementation</h3><p>How to add JSON Web Token to protect your web APIs and authenticate users</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b33d1rB5_1CGRV_00HXDlw.png" /></figure><h3>About</h3><p>This is part 2 of<strong> </strong><a href="https://vaygeth.medium.com/net-core-adding-jwt-claims-to-web-api-part-1-the-setup-313bb7c93c62"><strong>.NET Core — Adding JWT Claims To Web API Part 1 The Setup</strong>. Make sure to follow Part 1</a></p><h3>Recap for What We Going To Build</h3><p>A web API that allows users to</p><ol><li>Sign Up (To obtain JWT token)</li><li>Sign In (To obtain JWT token)</li><li>Get User Profile API (Protected by JWT authorization)</li></ol><h3>The APIs implementations</h3><p>Create File named<strong> AccountController</strong>.cs or whatever you like to name it under the <strong>Controllers</strong> folder. Note for simplicy I’m not going to implement it using <strong>Services/Repository</strong> design patterns. <em>Note you need to handle stuff like some of business rules or validation that suits your needs.</em></p><p>The controller will contain 3 Actions:</p><ol><li><strong>SignUp </strong>Action Controller, where new users can register and obtain an profile/account into our system like email, username,password..etc</li><li><strong>SignIn </strong>Action Controller, where users can login and obtain a JWT Authorization claim to be used next API</li><li><strong>GetMyProfile </strong>Action Controller, where this API will require users to be logged-in and pass JWT Authroizating token in order to fetch their Profile like email or username …etc</li></ol><h4>Controllers Setup</h4><p>We will inject 3 objects in <strong>AccountController </strong>constructor by .NET core dependency injection system.</p><ol><li><strong>AppDbContext </strong>the objects that allows us to communicate with our Database and manage it through Entity Framework ORM system.</li><li><strong>JWTBearerTokenSettings </strong>the objects that carries our JWT options from <em>appsettings.json</em> like</li><li><strong>UserManager </strong>which allows access to ASPNetCore User Identity to manage Users data and configurations</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9202a5ddb2db693ef109996fd9de9a5a/href">https://medium.com/media/9202a5ddb2db693ef109996fd9de9a5a/href</a></iframe><p>Now that construction for AccountController is completed we going to add our actions</p><h4>SignUp API</h4><p>This is <strong>SignUp </strong>web service that allows “anonymous users” to register into our web API and store his information into our database. First we going to create a <strong>ViewModel </strong>Folder and add a class we named it <strong>SignUpData.cs</strong> for our <strong>SignUp API</strong> that wraps up user request objects containing following in order to be stored in our database.</p><ol><li>Email</li><li>Username</li><li>Password</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b836d49c8ac4c8d53ee6ba62d5fac724/href">https://medium.com/media/b836d49c8ac4c8d53ee6ba62d5fac724/href</a></iframe><p>Now that the <strong>ViewModel </strong>is added, we can add an Action Method inside our <strong>AccountController.cs . </strong>Also after the success of user registration, we will generate a JWT token based on the user registered information to provide the client a JWT claim (token), therefore we also going to add a none Controller Action method called <strong>GenerateJWTToken.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9fc294efd9c84138ed0dca6802da6e65/href">https://medium.com/media/9fc294efd9c84138ed0dca6802da6e65/href</a></iframe><h4>Test SignUp Web Service</h4><p>I’m going to use Postman client to test our APIs. Run the app through IDE or type the following in the Terminal</p><pre><strong>dotnet run</strong></pre><p>And do a Post request passing <strong>SignUpData</strong>, you should receive the JWT token</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uNLZZFE990pEFSBI3a-JDg.png" /></figure><h4>SignIn API</h4><p>The <strong>SignIn </strong>web service will allow already registered users to <strong>SignIn </strong>by login with Email &amp; password and then obtaining a JWT claim “token” that will allow him to access protected web-services by calling it and passing it JWT claim in the header.</p><p>Before all of that let’s add a class wrapper that accepts Sign In information for <strong>SignIn </strong>webservices as <strong>ViewModel </strong>class named <strong>SignInData.cs</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/682c6a73bc0c0ddd7394067828b6fcb1/href">https://medium.com/media/682c6a73bc0c0ddd7394067828b6fcb1/href</a></iframe><p>Now we define <strong>SignIn </strong>Controller Action method and the a method that passed user email &amp; password that validates it and then generating the JWT Claim if was valid credentials called <strong>ValidateUserCredentials</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/40091ec405a7b75c8e2915cb4faf7bcd/href">https://medium.com/media/40091ec405a7b75c8e2915cb4faf7bcd/href</a></iframe><h4>Test SignIn Web Service</h4><p>Rerun the app through the IDE or hit <strong>Ctrl+C</strong> in the previously active Terminal to interrupt and the the following command in the Terminal</p><pre><strong>dotnet run</strong></pre><p>And do a Post request passing it Email &amp; Password for user whom already registered user in the SignUp section. If the credentials are correct, you should receive the JWT token in the web service response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5-GiprWj_H6LzVMrn4HpGQ.png" /></figure><h4>GetMyProfile API</h4><p>The last Controller action method, will be protected by an Authorization as denoted by [Authorize] tag/annotation to a middleware that expects the client/request containing a JWT token in the header (Bearer token) in order to process the request, otherwise it will return an <strong>HTTP 401Unauthorized</strong></p><p>however if the request contains JWT claim then it will return the User information like <em>Email</em>, <em>Username </em>and his <em>PhoneNumber </em>in a wrapper class called <strong>UserProfile</strong>.</p><p>Create <strong>UserProfile.cs</strong> under <strong>ViewModels</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8992ded7f15392def45d13e907da1424/href">https://medium.com/media/8992ded7f15392def45d13e907da1424/href</a></iframe><p>And add <strong>GetMyProfile </strong>Controller Action Method. Note the [Authorize] annotation above the [Route]</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c4f838ce6e832610316863e5f59a66d/href">https://medium.com/media/5c4f838ce6e832610316863e5f59a66d/href</a></iframe><h4>Test SignIn Web Service</h4><p>Testing <strong>GetMyProfile </strong>API will require previously generate Token by using the <strong>SignIn </strong>(or <strong>SignUp</strong>) web services in the request header as Bearer token. If the tokens were not expires it will</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WqQP912_g0XyoGvJWpRpCw.png" /></figure><p>that’s all for this tutorial.</p><h3>Source</h3><p>You can find the complete source code on <a href="https://github.com/vaygeth89/tutorial-dotnet-JWTProtectedAPI.git">github here.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b6c2ca6fe98" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[.NET Core —Adding  JWT Claims To Web API — Part 1 The Setup]]></title>
            <link>https://vaygeth.medium.com/net-core-adding-jwt-claims-to-web-api-part-1-the-setup-313bb7c93c62?source=rss-37cce710294------2</link>
            <guid isPermaLink="false">https://medium.com/p/313bb7c93c62</guid>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Vaygeth (Abdulmohsen)]]></dc:creator>
            <pubDate>Tue, 17 Nov 2020 21:14:05 GMT</pubDate>
            <atom:updated>2020-11-18T22:37:51.218Z</atom:updated>
            <content:encoded><![CDATA[<h3>.NET Core —Adding JWT Claims To Web API — Part 1 The Setup</h3><p>How to add JSON Web Token to protect your web APIs and authenticate users</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b33d1rB5_1CGRV_00HXDlw.png" /></figure><h3>What We Going To Build</h3><p>A web API that allows users to</p><ol><li>Sign Up (obtain JWT token)</li><li>Sign In to obtain JWT token</li><li>Get User Profile API (Protected by JWT authorization)</li></ol><h3>The Required Packages &amp; CLIs</h3><ol><li><a href="http://microsoft.aspnetcore.authentication.jwtbearer/">ASP Core JWT</a> to add authorization to our API</li><li><a href="https://www.nuget.org/packages/Microsoft.EntityFrameworkCore.SqlServer/">Any Database Package, I’m SqlServer</a> to connect to SQL Server Database and store data</li><li><a href="https://www.nuget.org/packages/Microsoft.Extensions.Identity.Core/">Entity framework Identity</a> to facilitate Database ORM and handle migrations</li><li><a href="https://www.nuget.org/packages/Microsoft.EntityFrameworkCore.Design/">Entity Framework Core Design</a> a required package for database</li><li><a href="https://www.nuget.org/packages/dotnet-ef/">Entity Framework CLI</a> to facilitate migrations and database changes</li></ol><p>Here shortcut if you are using dotnet CLI</p><pre>dotnet new webapi -n JWTProtectedAPI</pre><pre>dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer</pre><pre>dotnet add package Microsoft.EntityFrameworkCore.SqlServer </pre><pre>dotnet add package Microsoft.AspNetCore.Identity.EntityFrameworkCore</pre><pre>dotnet add package Microsoft.EntityFrameworkCore.Design </pre><pre>dotnet tool install --global dotnet-ef </pre><h3>The Setup</h3><h4>appsettings.json</h4><p>Open <strong>appsettings.json </strong>and add JWT configurations. these configurations used to modify the JWT settings like when it’s expires, the Secret Key used to authorize the claim….etc. <strong>ExpiryTimeInMinutes </strong>is set for JWT to expire in 2 hours, you can set it to whatever you want.</p><p>Also add your Connection String, I’m using my own config for SqlServer</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4872222564341c63846cbbdb067682f5/href">https://medium.com/media/4872222564341c63846cbbdb067682f5/href</a></iframe><h4><strong>Startup.cs</strong></h4><p>Inside <strong>ConfigureServices </strong>method add the following to configure our AppDbContext and Connection String as well the coming of JWT setup. Note the Sign In/Password security policy, make sure you update it to suits your security policies</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/122f7af9c5b483ec582d88fb60f27ed8/href">https://medium.com/media/122f7af9c5b483ec582d88fb60f27ed8/href</a></iframe><p>Also inside <strong>Startup.cs </strong>after <strong>ConfigureServices() </strong>define <strong>setUpBearerJwtAuth</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/10a3f4f23538a98ff0679772615afc83/href">https://medium.com/media/10a3f4f23538a98ff0679772615afc83/href</a></iframe><p>Also inside <strong>Startup.cs</strong> in <strong>Configure(IApplicationBuilder app, IWebHostEnvironment env)</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f86c674ea55f6da7ba0ac5ee905bb0d/href">https://medium.com/media/7f86c674ea55f6da7ba0ac5ee905bb0d/href</a></iframe><p><strong>AppDbContext.cs</strong></p><p>Create <strong>AppDbContext </strong>class conventionally under <strong>Models</strong> folder in the root of your project folder <strong>(JWTProtectedAPI/Models/AppDbContext.cs) </strong>and add the following code.</p><p>We going to use ASP core identity for creating Users so that’s why our DB Context extending <strong>IdentityDbContext&lt;IdentityUser&gt;</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d7584b28cd277e80554d798c9f67cbe0/href">https://medium.com/media/d7584b28cd277e80554d798c9f67cbe0/href</a></iframe><p><strong>Migrations and Database Update</strong></p><p>To create migrations and apply them into the database run the following commands.</p><pre>dotnet ef migrations add Init -c AppDbContext</pre><pre>dotnet ef database update -c AppDbContext</pre><p>What we did is tell our framework to create Asp Dotnet JWT identity configurations and tables migrations and apply them into our database.</p><p>You will see several new tables if above were successful</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/213/1*ts2si-9ltV5XbWpme2liaw.png" /><figcaption>JWTProtectedAPI database</figcaption></figure><h4>Conclusion for Part 1</h4><p>This concludes Part 1 for .NET JWT Setup, <a href="https://vaygeth.medium.com/net-core-adding-jwt-claims-to-web-api-part-2-the-apis-implementation-5b6c2ca6fe98"><strong>Part 2 The APIs implementation</strong></a> will be published this Friday.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=313bb7c93c62" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Minimalism: Onboarding Logic]]></title>
            <link>https://vaygeth.medium.com/flutter-minimalism-onboarding-logic-b4f00d1731a2?source=rss-37cce710294------2</link>
            <guid isPermaLink="false">https://medium.com/p/b4f00d1731a2</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[how]]></category>
            <category><![CDATA[sharedpreferences]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[onboarding]]></category>
            <dc:creator><![CDATA[Vaygeth (Abdulmohsen)]]></dc:creator>
            <pubDate>Sun, 21 Jun 2020 23:17:35 GMT</pubDate>
            <atom:updated>2020-06-21T23:18:06.720Z</atom:updated>
            <content:encoded><![CDATA[<p>Minimalist approach for your Flutter app to check if it was freshly installed and downloaded</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*Xu2zc4Y43AUWSB4c4vbvrQ.png" /></figure><h4>About Flutter Minimalism Guide</h4><p>The guide aims to help Flutter developers to implement common app use-cases &amp; scenarios with reduced complications and less overhead of</p><ol><li>Less waste of time explanations, and more into solving the problem</li><li>Less usage of abstraction and less over engineered architectures</li><li>Less complicated code samples &amp; outdated libraries</li></ol><h4>What Flutter Minimalism is not about</h4><p>The guide won’t go explaining Dart/Flutter concepts like asynchronous programming or Flutter Widgets basics, as this is just a guide not a tutorial material.</p><h4>The Use-case: Onboarding Logic</h4><p>Most apps nowadays offer their first time user (freshly installed apps) an <strong>Onboarding</strong> Journey which welcomes help users to get familiar with the app. In this tutorial series, I will demonstrate how to implement this flow in simple fashion.</p><p>Let’s say we want the to distinguish if the user just freshly downloaded the app from the App Store or Google-Play and opened the app for the first time, then it will take him to the <strong>Onboarding Page</strong>, otherwise if the user open the app a second time, or third time..etc it will take him to the<strong> Home Page </strong>instead</p><h3>Logic Flow</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-q5R0RO5_jirnj7W-QQ0jg.png" /></figure><h3><strong>The Implementation</strong></h3><h4><strong>Plugins</strong></h4><p>First we need our app to store a simple persistent flag on the device that will be checked whenever the user open the apps to demonstrate whether the app was fresh/first time installed.</p><p>The simplest way to do this is using the <a href="https://pub.dev/packages/shared_preferences#-readme-tab-">shared_preferences</a> library. Add it to your <strong>pubspec.yaml, save the file and reload the package.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/535/1*zzVkzr9d_EgQGtmLLvSU_Q.png" /></figure><blockquote><strong>Make sure if you are already running/debugging the app, then perform a restart or stop and rerun the app so the plugin generate the required binaries to run correctly.</strong></blockquote><h4>The Project</h4><p>For simplicity the project will consist only of 2 files inside Lib folder</p><ul><li>main.dart</li><li>shared_preferences_manager.dart</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/276/1*ylJT_UgjcCzuEzYRsXmCtg.png" /><figcaption>Lib folder files</figcaption></figure><h4>shared_preferences_manager.dart</h4><p>Create the shared_preferences_manager.dart inside the lib folder, and add the following class that will contain a method to fetch and store the <strong>isFreshlyInstalled</strong> flag in the device shared preferences storage</p><pre>import &#39;package:shared_preferences/shared_preferences.dart&#39;;<br></pre><pre>class SharedPreferencesManager {</pre><pre>//Unique key that can be used to identify is feshly installed flag</pre><pre>static const String IS_FRESHLY_INSTALLED_PREFERENCE_KEY =</pre><pre>&quot;is_freshly_installed&quot;;<br></pre><pre>Future&lt;bool&gt; isFreshInstalled() async {</pre><pre>var pref = await SharedPreferences.getInstance();</pre><pre>bool isFreshlyInstalled = pref.getBool(IS_FRESHLY_INSTALLED_PREFERENCE_KEY);</pre><pre>if (isFreshlyInstalled == null) {</pre><pre>//null means if fresh installed and flag wasn&#39;t stored before</pre><pre>//so we save false into pref incase this flag is needed again or else where after fresh installation</pre><pre>return await pref.setBool(IS_FRESHLY_INSTALLED_PREFERENCE_KEY, false);</pre><pre>} else {</pre><pre>return isFreshlyInstalled;</pre><pre>}</pre><pre>}</pre><pre>}</pre><h4>main.dart</h4><p>For simiplicity, we gona put the remaining of the widgets in the main.dart file</p><pre>import &#39;package:check_is_fresh_install/shared_preferences_manager.dart&#39;;</pre><pre>import &#39;package:flutter/material.dart&#39;;</pre><pre>void main() {</pre><pre>runApp(MyApp());</pre><pre>}</pre><pre>class MyApp extends StatelessWidget {</pre><pre>@override</pre><pre>Widget build(BuildContext context) {</pre><pre>return MaterialApp(</pre><pre>title: &#39;Flutter Demo&#39;,</pre><pre>theme: ThemeData(</pre><pre>primarySwatch: Colors.blue,</pre><pre>visualDensity: VisualDensity.adaptivePlatformDensity,</pre><pre>),</pre><pre>//By default makes your app always load the StartUpWidget</pre><pre>home: StartUpWidget(),</pre><pre>);</pre><pre>}</pre><pre>}</pre><pre>class StartUpWidget extends StatelessWidget {</pre><pre>@override</pre><pre>Widget build(BuildContext context) {</pre><pre>return Scaffold(</pre><pre>body: Center(</pre><pre>child: FutureBuilder&lt;bool&gt;(</pre><pre>future: SharedPreferencesManager().isFreshInstalled(),</pre><pre>builder: (context, isFreshInstalledSnapshot) {</pre><pre>if (isFreshInstalledSnapshot.hasData) {</pre><pre>if (isFreshInstalledSnapshot.data) {</pre><pre>//You can return for example your onboarding widget/page</pre><pre>return OnboardingPage();</pre><pre>} else {</pre><pre>//You can return your HomePage() or whatever widget/page</pre><pre>return HomePage();</pre><pre>}</pre><pre>} else {</pre><pre>//For good user Experiance you can show Your App Logo/loading Screen</pre><pre>return Center(</pre><pre>child: CircularProgressIndicator(),</pre><pre>);</pre><pre>}</pre><pre>}),</pre><pre>),</pre><pre>);</pre><pre>}</pre><pre>}</pre><pre>class OnboardingPage extends StatelessWidget {</pre><pre>const OnboardingPage({Key key}) : super(key: key);</pre><pre>@override</pre><pre>Widget build(BuildContext context) {</pre><pre>return Scaffold(</pre><pre>appBar: AppBar(),</pre><pre>body: Center(</pre><pre>child: Text(&quot;My Onboarding Page&quot;),</pre><pre>),</pre><pre>);</pre><pre>}</pre><pre>}</pre><pre>class HomePage extends StatelessWidget {</pre><pre>const HomePage({Key key}) : super(key: key);</pre><pre>@override</pre><pre>Widget build(BuildContext context) {</pre><pre>return Scaffold(</pre><pre>appBar: AppBar(),</pre><pre>body: Center(</pre><pre>child: Text(&quot;My Home Page&quot;),</pre><pre>),</pre><pre>);</pre><pre>}</pre><pre>}</pre><h4>The source code</h4><p>The source code is also available on the <a href="https://github.com/vaygeth89/flutter_tutorial_is_freshly_installed">repo here</a></p><h4>Feedback</h4><p>Share your feedback on what should I write about for <strong>Flutter Minimalism Series</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b4f00d1731a2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Web: Dart’s HTML & JavaScript Proxying to Access the DOM]]></title>
            <link>https://vaygeth.medium.com/flutter-web-darts-html-javascript-proxying-to-access-the-dom-69e2008eb320?source=rss-37cce710294------2</link>
            <guid isPermaLink="false">https://medium.com/p/69e2008eb320</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web]]></category>
            <dc:creator><![CDATA[Vaygeth (Abdulmohsen)]]></dc:creator>
            <pubDate>Fri, 11 Oct 2019 23:42:17 GMT</pubDate>
            <atom:updated>2019-10-12T00:03:21.976Z</atom:updated>
            <content:encoded><![CDATA[<h3>Early Adaption for Flutter Web: Dart’s HTML &amp; JavaScript Proxying</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D5HYFARy1U-T4E9OtK3LMA.png" /><figcaption><a href="https://flutter.dev/images/Dart-framework-v-browser-framework.png">https://flutter.dev/images/Dart-framework-v-browser-framework.png</a></figcaption></figure><p>This is part of a series aimed to demonstrate of using Flutter framework as web app covering different use-cases.</p><h3>About the article</h3><p>This article will cover the ability of Flutter &amp; Dart to access more features than the Flutter SDK offers of using the Widget systems that is being used to develop mobile apps for iOS &amp; Android platforms, like the browser’s <strong>DOM</strong> features using <strong>Dart’s</strong> <strong>HTML</strong> &amp; <strong>JavaScript</strong> proxying (interlope).</p><h3>Requirements</h3><ul><li>Assumes you are already setup Flutter SDK and Flutter CLI</li><li>Assumes you already have some experience with some programming languages and Flutter framework.</li><li>Installed Google Chrome Browser</li><li>Your Flutter’s SDK is set to read from the master branch (where Flutter libraries resides), you can set it up by running the following commands:</li></ul><pre><em>Point Flutter SDK to Master Branch</em><strong><br>flutter channel master</strong></pre><pre><em>Updates Flutter SDK</em><strong><br>flutter upgrade</strong></pre><pre><em>Enable Flutter for Web Builds</em><strong><br>flutter config --enable-web</strong></pre><pre><strong>flutter create flutter_for_web_part1</strong></pre><pre><strong>cd flutter_for_web_part1</strong></pre><pre><em>Runs the app on chrome</em><strong><br>flutter run -d chrome</strong></pre><h3>The Demo App</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*ftPo4R5MZPj8_cSmLHRJYQ.png" /><figcaption>The application</figcaption></figure><p>The app is very simple, it will contain 2 Images &amp; floating action button that if clicked it will execute certain HTML &amp; JavaScripts interlopes functionalities:</p><p><strong>Flutter Project</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/264/1*_XoeYaBOZClcGfvONKtMUQ.png" /><figcaption>Only main.dart</figcaption></figure><p>The projects only consists of single dart file <strong>main.dart. </strong>For simplicity <strong>main.dart</strong> will contain the whole app.</p><h3>main.dart</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc24684b6a28aab2c0faf0aff0aa46a4/href">https://medium.com/media/dc24684b6a28aab2c0faf0aff0aa46a4/href</a></iframe><p>The important snippets in the <strong>main.dart</strong> file is the following:</p><p><strong>The library imports</strong></p><p>Here we are importing Dart’s proxying libraries for both <strong>HTML &amp; JavaScrip</strong>t and giving an alias using <strong>as keyword</strong> to them in order to make our code more readable.</p><pre><strong>import &#39;dart:html&#39; as html;<br>import &#39;dart:js&#39; as js;</strong></pre><p><strong>The Buttons</strong></p><pre><em>// InkWell is widget used to add taps &amp; gestures events to child</em></pre><pre><strong>InkWell(</strong></pre><pre><strong>onTap: () {</strong></pre><pre><strong>html.window.localStorage.addEntries([</strong></pre><pre><strong>MapEntry(</strong></pre><pre><strong>&quot;data&quot;, &quot;this data is stored on browser local storage&quot;)</strong></pre><pre><strong>]);</strong></pre><pre><strong>js.JsObject jsonObject = js.JsObject(js.context[&#39;Object&#39;]);</strong></pre><pre><strong>jsonObject[&quot;message&quot;] = &#39;Flutter Web&#39;;</strong></pre><pre><strong>js.context[&quot;console&quot;].callMethod(</strong></pre><pre><strong>&quot;log&quot;, [&#39;internalRoute&#39;, &#39;\n&#39;, jsonObject[&quot;message&quot;]]);</strong></pre><pre><strong>},<br> child: Image.network(&quot;https://flutter.dev/assets/flutter-lockup-4cb0ee072ab312e59784d9fbf4fb7ad42688a7fdaea1270ccf6bbf4f34b7e03f.svg&quot;,</strong></pre><pre><strong>width: 200,</strong></pre><pre><strong>height: 200,),<br>),</strong></pre><pre><strong>InkWell(onTap: () {</strong></pre><pre><strong>String externalUrl =</strong></pre><pre><strong>&#39;https://github.com/vaygeth89/flutter_for_web_part1&#39;;</strong></pre><pre><strong>html.window.alert(&quot;You&#39;re being redirected to \n $externalUrl&quot;);</strong></pre><pre><strong>js.context.callMethod(&quot;open&quot;, [externalUrl]);</strong></pre><pre><strong>},</strong></pre><pre><strong>child: Image.network(</strong></pre><pre><strong>&quot;https://github.githubassets.com/images/modules/logos_page/GitHub-Mark.png&quot;,</strong></pre><pre><strong>width: 100,</strong></pre><pre><strong>height: 100,<br>),<br>)</strong></pre><pre><strong>//Rest of the code<br>//...<br>//...<br>//...</strong></pre><h3>Tapping Flutter Logo</h3><p>When you tap Flutter’s logo the app will execute</p><h4>1- Save some data to local storage</h4><pre>html.window.localStorage.addEntries([</pre><pre>MapEntry(&quot;data&quot;, &quot;this data is stored on browser local storage&quot;)</pre><pre>]);</pre><h4>2- Create an Object and assign data for it using JavaScript DOM objects</h4><pre>//Creates json object from javascript library<br><strong>js.JsObject jsonObject = js.JsObject(js.context[&#39;Object&#39;]);</strong></pre><pre>//Create object {&quot;message&quot;:&quot;Flutter Web&quot;}<br><strong>jsonObject[&quot;message&quot;] = &#39;Flutter Web&#39;;</strong></pre><h4>3- Print Data to Browser Console using console.log()</h4><pre>//Executes javascripts console.log();<br><strong>js.context[&quot;console&quot;].callMethod(&quot;log&quot;, <br>[&#39;still in the same page&#39;, &#39;\n&#39;, jsonObject[&quot;message&quot;]]);</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*JJntLZeNYQjVe-2I3ezpbg.png" /></figure><p>The js.context[“object”].callMethod(“method name”, options) grants you access to javascripts DOM methods like console logs, open url, prompts…etc, refer to <a href="https://api.dartlang.org/stable/2.5.2/dart-js/dart-js-library.html">https://api.dartlang.org/stable/2.5.2/dart-js/dart-js-library.html</a></p><h3>Tapping Github Logo</h3><p>When you tap on Github’s Logo the app will show <strong>Alert</strong> popup message and redirect you to this tutorial Github repository using</p><pre>String externalUrl =&#39;https://github.com/vaygeth89/flutter_for_web_part1&#39;;</pre><pre>html.window.alert(&quot;You&#39;re being redirected to \n $externalUrl&quot;);<br>js.context.callMethod(&quot;open&quot;, [externalUrl])</pre><h3>Tapping Floating Action Button</h3><p>When you tap the floating action button the app will reload the current page</p><pre>floatingActionButton: FloatingActionButton(<br>child: Icon(Icons.refresh),<br>onPressed: (){<br><strong>html.window.location.reload();</strong><br> },<br>),</pre><h3>Summary</h3><p>The takes is not limited to these features, you can do more to access the <strong>DOM</strong> as if you can writing vanilla <strong>HTML</strong> &amp; <strong>JavaScript</strong> to manipulate the <strong>DOM like accessing getDocumentById &amp; getDocumentByElement, StyleSheets </strong>…etc, refer to for more examples <a href="https://dart.dev/tutorials/web/low-level-html/add-elements">https://dart.dev/tutorials/web/low-level-html/add-elements</a></p><h3>References</h3><p>Flutter for web: <a href="https://flutter.dev/web"><strong>https://flutter.dev/web</strong></a></p><p>Tutorial Github repository: <a href="https://github.com/vaygeth89/flutter_for_web_part1"><strong>https://github.com/vaygeth89/flutter_for_web_part1</strong></a></p><p>Dart’s HTML Low Level examples: <a href="https://dart.dev/tutorials/web/low-level-html/add-elements"><strong>https://dart.dev/tutorials/web/low-level-html/add-elements</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69e2008eb320" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reactive Flutter Todo App using  BLoC Design Pattern]]></title>
            <link>https://vaygeth.medium.com/reactive-flutter-todo-app-using-bloc-design-pattern-b71e2434f692?source=rss-37cce710294------2</link>
            <guid isPermaLink="false">https://medium.com/p/b71e2434f692</guid>
            <category><![CDATA[bloc]]></category>
            <category><![CDATA[sqlite]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <dc:creator><![CDATA[Vaygeth (Abdulmohsen)]]></dc:creator>
            <pubDate>Sun, 24 Feb 2019 21:05:44 GMT</pubDate>
            <atom:updated>2019-03-15T17:44:29.208Z</atom:updated>
            <content:encoded><![CDATA[<h3>Flutter: Todo App using BLoC Design Pattern with SQLite</h3><p>With many engineering design patterns emerges that help structure your Flutter projects to allows your code perform better, structure it to make it adoptable to new changes, or makes it reusable. In this article, I will display the making of the classical <strong>Todo </strong>app using Flutter which will store &amp; interact with it’s data reactively on its local database storage using SQLite. You can find project <a href="https://github.com/vaygeth89/reactive_flutter_todo_database_app">git repository here</a> for complete project.</p><p>The app will cover different architectural design patterns practices such as:</p><ul><li>Google&quot;s Business Logic Component Architecture Design Pattern (BLoC)</li><li>Reactive Programming using Dart streams (Similar to <a href="https://github.com/reduxjs/redux">Redux</a>)</li><li>Asynchronous events &amp; operations (Future events)</li><li>CRUD operations I/O using Local Database</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*FdVQPuPDd1ZXGhwNU6qHWw.jpeg" /><figcaption>The Flutter Todo mobile app</figcaption></figure><h3><strong><em>Prerequisites:</em></strong></h3><p>This article will be lengthy and focused for intermediate developers that are fairly familiar with Flutter framework, as this article won’t cover all the details like the basics of Flutter or Dart syntax &amp; semantics.</p><h3>The Todo App</h3><p>Our target is to create a single page app that can perform CRUD (Create, Read, Update, Delete) operations on the Todo items covering mentioned design patterns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/1*rzgctaG1fIotce8QMEEzoA.png" /></figure><p>The will have the following abilities:</p><ul><li>Create <strong>Todo</strong> item by clicking on Floating Action Button (+) on the navigation bar</li><li>Update <strong>Todo</strong> by checking the checkbox to mark the Todo item as done/completed or vise versa.</li><li>Read <strong>Todos</strong> by fetching all created it’s records items or when searching for description by clicking the Search Icon on the navigation bar.</li><li>Delete <strong>Todo</strong> item by swiping the Card horizontally to right or left.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BVqmGZGfD4X0Z7eF9XjItg.png" /></figure><h3>Flutter Project</h3><p>Start creating Flutter project and name it whatever (<strong><em>I named it reactive_todo_app, but make sure when you import the dart packages to use your project name not reactive_todo_app if you were copying the code).</em></strong></p><p>Go to your <a href="https://github.com/vaygeth89/reactive_flutter_todo_database_app/blob/master/pubspec.yaml">pubspec.yaml</a> file (found under your main project folder) and add the two packages (<a href="https://pub.dartlang.org/packages/sqflite">sqflite </a>&amp; <a href="https://pub.dartlang.org/packages/path_provider">path_provider</a>) under dependencies. Note the packages version may differ, as if now we have sqflite v1.1.0 &amp; path_provider v0.5.0.</p><ol><li>Sqflite is dart adapter extension for managing device SQLITE database</li><li>Path_Provider is an extension that help facilitate the common device storage path, in our case will be used in conjunction with Sqflite to store database on device.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/1*AM57-8A_U7tzyZvQZP700Q.png" /><figcaption><a href="https://github.com/vaygeth89/reactive_flutter_todo_database_app/blob/master/pubspec.yaml">pubspec.yaml</a></figcaption></figure><h3>Project Structure (Packages &amp; Files)</h3><p>Create the project <strong>packages </strong>under the <strong>lib</strong> directory/folder as shown and add its siblings dart files accordingly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/308/1*VHcn0nhYhhj6a_5iTnHOdg.png" /><figcaption>The Packages &amp; Files Structure</figcaption></figure><p><strong>The Todo Model/POJO (todo.dart)</strong></p><pre><em>class </em>Todo {<br>  <strong>int id;<br>  <em>//description is the text we see on<br>  //main screen card text<br>  </em>String description;<br>  <em>//isDone used to mark what Todo item is completed<br>  </em>bool isDone = <em>false</em>;</strong></pre><pre>  <em>//When using curly braces { } we note dart that<br>  //the parameters are optional<br>  </em>Todo({<em>this</em>.id, <em>this</em>.description, <em>this</em>.isDone = <em>false</em>});<br></pre><pre>  <em>factory </em>Todo.fromDatabaseJson(Map&lt;String, <em>dynamic</em>&gt; data) =&gt; Todo(<br>    <em>//This will be used to convert JSON objects that<br>    //are coming from querying the database and converting<br>    //it into a Todo object</em></pre><pre><em>        </em>id: data[&#39;id&#39;],<br>        description: data[&#39;description&#39;],</pre><pre>        <em>//Since sqlite doesn&#39;t have boolean type for true/false<br>        //we will 0 to denote that it is false<br>        //and 1 for true<br>        </em>isDone: data[&#39;is_done&#39;] == 0 ? <em>false </em>: <em>true</em>,<br>      );</pre><pre>  Map&lt;String, <em>dynamic</em>&gt; toDatabaseJson() =&gt; {<br>    <em>//This will be used to convert Todo objects that<br>    //are to be stored into the datbase in a form of JSON</em></pre><pre><em>        </em>&quot;id&quot;: <em>this</em>.id,<br>        &quot;description&quot;: <em>this</em>.description,<br>        &quot;is_done&quot;: <em>this</em>.isDone == <em>false </em>? 0 : 1,<br>      };<br>}</pre><p>Our Todo model will have 3 fields as shown, <strong><em>id</em></strong>(auto-generated by database), <strong><em>description </em></strong>(the text body for <strong>Todo</strong>), and <strong><em>isDone </em></strong>(to denote whether the item was completed). We add <strong>toDatabaseJson()</strong> method in order to convert our <strong>Todo</strong> instance into a JSON format that <strong>sqflite </strong>adapters will use in order to save it on the database in form of Table record, I will demonstrated it in coming <strong>database.dart</strong> class. Vise versa the factory method<strong> fromDatabaseJson(….</strong>) will convert <strong>sqflite </strong>results (of type JSON) fetched from the database into <strong>Todo </strong>model instance.</p><p><strong>Creating our Database (database.dart)</strong></p><pre><em>import </em>&#39;dart:async&#39;;<br><em>import </em>&#39;dart:io&#39;;</pre><pre><em>import </em>&#39;package:path/path.dart&#39;;<br><em>import </em>&#39;package:path_provider/path_provider.dart&#39;;<br><em>import </em>&#39;package:sqflite/sqflite.dart&#39;;</pre><pre><strong><em>final </em>todoTABLE = &#39;Todo&#39;;</strong><br><em>class </em>DatabaseProvider {<br>  <em>static final </em>DatabaseProvider dbProvider = DatabaseProvider();</pre><pre>  <strong>Database _database;</strong></pre><pre>  Future&lt;Database&gt; <em>get </em>database <em>async </em>{<br>    <em>if </em>(_database != <em>null</em>) <em>return </em>_database;<br>    _database = <em>await </em>createDatabase();<br>    <em>return </em>_database;<br>  }</pre><pre>  createDatabase() <em>async </em>{<br>    Directory documentsDirectory = <em>await </em>getApplicationDocumentsDirectory();<br>   <strong> <em>//&quot;ReactiveTodo.db is our database instance name<br>    </em>String path = join(documentsDirectory.path, &quot;ReactiveTodo.db&quot;);</strong></pre><pre>    <em>var </em>database = <em>await </em>openDatabase(path,<br>        version: 1, onCreate: initDB, onUpgrade: onUpgrade);<br>    <em>return </em>database;<br>  }</pre><pre>  <em>//This is optional, and only used for changing DB schema migrations<br>  void </em>onUpgrade(Database database, int oldVersion, int newVersion) {<br>    <em>if </em>(newVersion &gt; oldVersion) {}<br>  }</pre><pre>  <strong><em>void </em>initDB(Database database, int version) <em>async </em>{<br>    <em>await </em></strong>database.execute<strong>(&quot;CREATE TABLE $todoTABLE (&quot;<br>        &quot;id INTEGER PRIMARY KEY, &quot;<br>        &quot;description TEXT, &quot;<br>        <em>/*SQLITE doesn&#39;t have boolean type<br>        so we store isDone as integer where 0 is false<br>        and 1 is true*/<br>        </em>&quot;is_done INTEGER &quot;<br>        &quot;)&quot;);<br>  }</strong><br>}</pre><p>The purpose of <strong>database.dart</strong> is to manage creating the database schema and expose the database instance <a href="https://www.dartlang.org/tutorials/language/futures"><strong>Asynchronously</strong></a><strong> </strong>for <strong>TodoDao </strong>to call. The whole upper boilerplate code of the class is mostly setting up the database instance for the app. The most important piece of these lines are usage of async, await keywords that makes the database creation in a asycncronous fashion. Any asycncronous operations done in darts has to return the Future type of the class <strong>Future&lt;T&gt;,</strong> in this case <strong>Future&lt;Database&gt;</strong>for database getter. As for<strong> i<em>nitDB(….)</em></strong> this is where our tables schema are created for the first time using database.execute method to create Todo table using SQL for each model member (id, description, isDone). Note that <strong><em>SQLITE </em></strong>doesn’t have <em>bool/boolean</em> type for our <strong>Todo </strong>member <strong>isDone</strong>, instead we have to take alternative path to store <em>boolean </em>values into the database; so we will use integer type where <strong>0 </strong>will denote <strong>isDone </strong>as <strong>False </strong>&amp; <strong>1</strong> will denote <strong>isDone </strong>as <strong>True</strong></p><p><strong>Data Access Object (todo_dao.dart)</strong></p><pre><em>import </em>&#39;dart:async&#39;;<br><em>import </em>&#39;package:reactive_todo_app/database/database.dart&#39;;<br><em>import </em>&#39;package:reactive_todo_app/model/todo.dart&#39;;<br><br><em>class </em><strong>TodoDao </strong>{<br>  <em>final </em>dbProvider = DatabaseProvider.dbProvider;<br><br>  <em>//Adds new Todo records<br>  </em>Future&lt;int&gt; createTodo(Todo todo) <em>async </em>{<br>    <em>final </em>db = <em>await </em>dbProvider.database;<br>    <em>var </em>result = db.insert(todoTABLE, todo.toDatabaseJson());<br>    <em>return </em>result;<br>  }<br><br>  <em>//Get All Todo items<br>  //Searches if query string was passed<br>  </em>Future&lt;List&lt;Todo&gt;&gt; <strong>getTodos({List&lt;String&gt; columns, String query})</strong> <em>async </em>{<br>    <em>final </em>db = <em>await </em>dbProvider.database;<br><br>    List&lt;Map&lt;String, <em>dynamic</em>&gt;&gt; result;<br>    <em>if </em>(query != <em>null</em>) {<br>      <em>if </em>(query.isNotEmpty)<br>        result = <em>await </em>db.query(todoTABLE,<br>            columns: columns,<br>            where: &#39;description LIKE ?&#39;,<br>            whereArgs: [&quot;%$query%&quot;]);<br>    } <em>else </em>{<br>      result = <em>await </em>db.query(todoTABLE, columns: columns);<br>    }<br><br>    List&lt;Todo&gt; todos = result.isNotEmpty<br>        ? result.map((item) =&gt; Todo.fromDatabaseJson(item)).toList()<br>        : [];<br>    <em>return </em>todos;<br>  }<br><br>  <em>//Update Todo record<br>  </em>Future&lt;int&gt; <strong>updateTodo(Todo todo)</strong> <em>async </em>{<br>    <em>final </em>db = <em>await </em>dbProvider.database;<br><br>    <em>var </em>result = <em>await </em>db.update(todoTABLE, todo.toDatabaseJson(),<br>        where: &quot;id = ?&quot;, whereArgs: [todo.id]);<br><br>    <em>return </em>result;<br>  }<br><br>  <em>//Delete Todo records<br>  </em>Future&lt;int&gt; <strong>deleteTodo(int id)</strong> <em>async </em>{<br>    <em>final </em>db = <em>await </em>dbProvider.database;<br>    <em>var </em>result = <em>await </em>db.delete(todoTABLE, where: &#39;id = ?&#39;, whereArgs: [id]);<br><br>    <em>return </em>result;<br>  }<br><br>  <em>//We are not going to use this in the demo<br>  </em>Future <strong>deleteAllTodos()</strong> <em>async </em>{<br>    <em>final </em>db = <em>await </em>dbProvider.database;<br>    <em>var </em>result = <em>await </em>db.delete(<br>      todoTABLE,<br>    );<br><br>    <em>return </em>result;<br>  }<br>}</pre><p><strong>TodoDao </strong>is dedicated to manage all local Database <em>Create Read Update Delete</em> (CRUD) operations for <strong><em>Todo </em></strong>model <em>asynchronously</em>. This will be main communicator between the <strong>TodoRepository </strong>&amp; our <strong>DatabaseProvider</strong> (database.dart) through following methods:</p><ul><li><em>createTodo(Todo todo) </em>creates new db records in <strong>Todo </strong>table by converting <strong>Todo </strong>model into JSON format and then stored in a form of table record.</li><li><em>getTodos({List&lt;String&gt; columns, String query}), </em>returns list all of <strong>Todo</strong> records or if query parameter were injected, then it filters all records using SQL <strong>WHERE</strong> to match the search</li><li><em>updateTodo(Todo todo), </em>update existing record by querying the database using the passed Todo instance id and update Todo’s description &amp; isDone</li><li><em>deleteTodo(int id), delete an existing record by querying the database using the passed Todo id.</em></li></ul><p><strong>TodoRepository (todo_repository.dart)</strong></p><pre><em>import </em>&#39;package:reactive_todo_app/dao/todo_dao.dart&#39;;<br><em>import </em>&#39;package:reactive_todo_app/model/todo.dart&#39;;<br><br><em>class </em><strong>TodoRepository </strong>{<br>  <strong><em>final </em>todoDao = TodoDao();</strong><br><br>  Future <strong>getAllTodos</strong>({String query}) =&gt; todoDao.getTodos(query: query);<br><br>  Future <strong>insertTodo</strong>(Todo todo) =&gt; todoDao.createTodo(todo);<br><br>  Future <strong>updateTodo</strong>(Todo todo) =&gt; todoDao.updateTodo(todo);<br><br>  Future <strong>deleteTodoById</strong>(int id) =&gt; todoDao.deleteTodo(id);<br><br>  <em>//We are not going to use this in the demo<br>  </em>Future <strong>deleteAllTodos</strong>() =&gt; todoDao.deleteAllTodos();<br>}</pre><p>In many architectural design patterns like <strong>BLoC </strong>&amp; <a href="https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93viewmodel"><strong>MVVM</strong></a><strong> </strong>the <em>repository</em> concept responsibility is to act as proxy bridge between different data sources provider that can orchestrate CRUD operations between them. In this project scope, I’m currently using one data source which is the local database through the usage of <strong>TodoDao</strong>, as shown in the above snippet it’s only calling <strong>TodoDao</strong> methods and there’s no much value for our project, but however imagine that in the future the business needs changes and now it requires our <strong>Todo </strong>app to fetch the <strong>Todos </strong>data from a backend service (<strong>TodoWebService</strong> for example) and sync it with the local database to provide offline app support for better user experience (UX), so all what you have to do is include <strong>TodoWebService</strong> class here and perform data syncing mechanism here between the local db (<strong>TaskDao</strong>) and the API source from different data sources.</p><p><strong>Business Logic Component (todo_bloc.dart)</strong></p><pre><em>import </em>&#39;package:reactive_todo_app/model/todo.dart&#39;;<br><em>import </em>&#39;package:reactive_todo_app/repository/todo_repository.dart&#39;;<br><br><br><em>import </em>&#39;dart:async&#39;;<br><br><em>class </em>TodoBloc {<br>  <em>//Get instance of the Repository<br>  final </em>_todoRepository = TodoRepository();<br><br>  <em>//Stream controller is the &#39;Admin&#39; that manages<br>  //the state of our stream of data like adding<br>  //new data, change the state of the stream<br>  //and broadcast it to observers/subscribers<br>  final </em>_todoController = StreamController&lt;List&lt;Todo&gt;&gt;.broadcast();<br><br>  <em>get </em>todos =&gt; _todoController.stream;<br><br>  TodoBloc() {<br>    getTodos();<br>  }<br><br>  getTodos({String query}) <em>async </em>{<br>    <em>//sink is a way of adding data reactively to the stream<br>    //by registering a new event<br>    </em>_todoController.sink.add(<em>await </em>_todoRepository.getAllTodos(query: query));<br>  }<br><br>  addTodo(Todo todo) <em>async </em>{<br>    <em>await </em>_todoRepository.insertTodo(todo);<br>    getTodos();<br>  }<br><br>  updateTodo(Todo todo) <em>async </em>{<br>    <em>await </em>_todoRepository.updateTodo(todo);<br>    getTodos();<br>  }<br><br>  deleteTodoById(int id) <em>async </em>{<br>    _todoRepository.deleteTodoById(id);<br>    getTodos();<br>  }<br><br>  dispose() {<br>    _todoController.close();<br>  }<br>}</pre><p><strong>TodoBloc() </strong>is our main reactive class/component that is responsible to manage our <strong>Todo </strong>data in a form of series/multiple <em>asynchronous events</em> (called <em>stream</em>). An <em>event </em>is the transition from data state to a new data state, for instance let’s say we have 7 <strong>Todo </strong>items in our <em>stream </em>that is expected to show for our users on the UI, and then through UI user decided to delete 1 <strong>Todo </strong>item to be 6 <strong>Todo </strong>items instead. In summary</p><ul><li><em>Stream </em>is a series of asynchronous (future) events of data</li><li>An event is the transition of current/old data state to a new state of data</li></ul><p>The supervisor/admin member of <strong>TodoBloc </strong>whom responsible to manage all of the previous and more is <strong>_todoController. To elaborate, _todoController can</strong></p><ol><li>Creating the stream of Todo data (by fetching Todo data asynchronously from the TodoRepository)</li><li>Adding a new data event using the sink (registering new event to change the state of the data <em>stream</em>)</li><li>Notifies/broadcasts the new state of the data <em>stream </em>to <em>subscribers/observers/listeners</em> as we will see in <strong>HomePage() </strong>class for <strong>StreamBuilder()</strong> widget.</li></ol><p><strong>HomePage() — The User Interface (home_page.dart)</strong></p><p><strong>HomePage() </strong>screen is a <strong>StatelessWidget </strong>that contains list of <strong>Todo </strong>Cards that is expected to accepts users inputs/outputs to perform the CRUD operation on the UI level. <strong>I will only show the important bits of the code</strong> since most of the code are mainly for UI designs, you can refer to the <a href="https://github.com/vaygeth89/reactive_flutter_todo_database_app/blob/master/lib/ui/home_page.dart">full implementation here of home_page.dart</a> . In following, our focus will be on initializing <strong>TodoBloc() </strong>that was mentioned to get our data <em>stream </em>of <strong>Todo</strong>. Second point to focus on the <strong>getTodoWidget()</strong> where this is the beginning of our Reactive UI components.</p><pre><em>class </em>HomePage <em>extends </em>StatelessWidget {<br>  HomePage({Key key, <em>this</em>.title}) : <em>super</em>(key: key);</pre><pre><strong><em>//Initialize our BLoC<br>final </em>TodoBloc todoBloc = TodoBloc();</strong><br>  <em>final </em>String title;</pre><pre> /*</pre><pre><strong>Too many lines of code not included here, refer back to github repo for the complete code</strong>.</pre><pre>*/<br> <strong>               child: Container(<br>                  <em>//This is where the magic starts<br>                    </em>child: getTodosWidget()</strong><br>                ))),<br>//.... rest of the HomePage class</pre><p><strong>Performing the UI READ via the stream</strong></p><pre>Widget <strong>getTodosWidget</strong>() {<br>  <strong><em>/*The StreamBuilder widget,<br>  basically this widget will take stream of data (todos)<br>  and construct the UI (with state) based on the stream<br>  */</em></strong><em><br>  return </em>StreamBuilder(<br>    <strong>stream: todoBloc.todos,</strong><br>    <strong>builder: (BuildContext context, AsyncSnapshot&lt;List&lt;Todo&gt;&gt; snapshot</strong>) {<br>      <em>return </em><strong>getTodoCardWidget</strong>(snapshot);<br>    },<br>  );<br>}</pre><p>First <strong>getTodoWidget()</strong> will construct the a <a href="https://docs.flutter.io/flutter/widgets/StreamBuilder-class.html"><strong>StreamBuilder </strong></a>widget that is responsible of building the remaining UI components based on the data <em>stream </em>coming from the <strong>TodoBloc </strong>we built (todo_bloc.dart). The <strong>StreamBuilder </strong>will <em>subscribe/observe/listen</em> to <strong>todoBloc.todos</strong> <em>stream in </em>order get notified by the <strong>TodoBloc </strong>whenever there’s event that changes <strong>Todos</strong> stream and update the values of the UI like number of <strong>Todos </strong>in the listview. The <em>stream </em>in our project is list of <strong>Todo </strong>objects (they are referred as snapshots by convention) that can be influenced by any event that change the state of data (like deleting <strong>Todo</strong> item, re-fecthing the list of <strong>Todo</strong>, sorting the list…etc).</p><p><strong>Performing the UI DELETE &amp; Update</strong></p><ol><li>To delete a Todo item, users can swipe the desired Todo card horizontally to the right or to the left to call out our <strong>TodoBloc </strong>via <strong>todoBloc.deleteTodoById(todo.id)</strong> method passing it the desired Todo item be deleted.</li><li>Same thing goes for updating a <strong>Todo </strong>item however via <strong>todoBloc.updateTodo(todo) </strong>but passing it the whole <strong>Todo</strong> object, whenever the user checks the checkbox to either mark it completed (isDone) or vise versa uncheck it to mark it not completed.</li></ol><pre>Widget getTodoCardWidget(AsyncSnapshot&lt;List&lt;Todo&gt;&gt; snapshot) {<br>  <em>/*Since most of our operations are asynchronous<br>  at initial state of the operation there will be no stream<br>  so we need to handle it if this was the case<br>  by showing users a processing/loading indicator*/<br>  if </em>(snapshot.hasData) {<br>    <em>/*Also handles whenever there&#39;s stream<br>    but returned returned 0 records of Todo from DB.<br>    If that the case show user that you have empty Todos<br>    */<br>    return </em>snapshot.data.length != 0<br>        ? ListView.builder(<br>            itemCount: snapshot.data.length,<br>            itemBuilder: (context, itemPosition) {<br>              Todo todo = snapshot.data[itemPosition];<br>              <em>final </em>Widget dismissibleCard = <em>new </em>Dismissible(<br>                background: Container(<br>                  child: Padding(<br>                    padding: EdgeInsets.only(left: 10),<br>                    child: Align(<br>                      alignment: Alignment.centerLeft,<br>                      child: Text(<br>                        &quot;Deleting&quot;,<br>                        style: TextStyle(color: Colors.white),<br>                      ),<br>                    ),<br>                  ),<br>                  color: Colors.redAccent,<br>                ),<br>                onDismissed: (direction) {<br>                  <strong><em>/*The magic<br>                  delete Todo item by ID whenever<br>                  the card is dismissed<br>                  */<br>                  </em>todoBloc.deleteTodoById(todo.id);</strong><br>                },<br>                direction: _dismissDirection,<br>                key: <em>new </em>ObjectKey(todo),<br>                child: Card(<br>                    shape: RoundedRectangleBorder(<br>                      side: BorderSide(color: Colors.grey[200], width: 0.5),<br>                      borderRadius: BorderRadius.circular(5),<br>                    ),<br>                    color: Colors.white,<br>                    child: ListTile(<br>                      leading: InkWell(<br>                        onTap: () {<br>                          <em>//Reverse the value<br>                          </em>todo.isDone = !todo.isDone;</pre><pre>                          <em>/*<br>                          </em><strong><em>Another magic.<br>                          This will update Todo isDone with either<br>                          completed or not<br>                          */<br>                          </em>todoBloc.updateTodo(todo);</strong><br>                        },<br>//.... the rest of getTodoCardWidget()</pre><p><strong>Performing the UI Todo Search</strong></p><p>We can search query Todo description using the <strong>todoBloc.getTodo(query)</strong></p><pre>// void _showTodoSearchSheet(BuildContext context){<br>//... rest of the code<br>Padding(<br>  padding: EdgeInsets.only(left: 5, top: 15),<br>  child: CircleAvatar(<br>    backgroundColor: Colors.indigoAccent,<br>    radius: 18,<br>    child: IconButton(<br>      icon: Icon(<br>        Icons.search,<br>        size: 22,<br>        color: Colors.white,<br>      ),<br>      <strong>onPressed: () {<br>        <em>/*This will get all todos<br>        that contains similar string<br>        in the textform<br>        */<br>        </em>todoBloc.getTodos(<br>            query:<br>                _todoSearchDescriptionFormController<br>                    .value.text);<br>        </strong><em>//dismisses the bottomsheet<br></em>        Navigator.pop(context);<br>      },<br>    ),<br>  ),<br>)</pre><p><strong>App Entry Point (main.dart)</strong></p><p>Lastly the <strong>MyApp </strong>is standard Widget nothing special about it. It will load up our only page <strong>HomePage() </strong>we went through previously.</p><pre><em>import </em>&#39;package:flutter/material.dart&#39;;<br><em>import </em>&#39;package:reactive_todo_app/ui/home_page.dart&#39;;<br><br><em>void </em>main() =&gt; runApp(MyApp());<br><br><em>class </em>MyApp <em>extends </em>StatelessWidget {<br>  @override<br>  Widget build(BuildContext context) {<br>    <em>return </em>MaterialApp(<br>      debugShowCheckedModeBanner: <em>false</em>,<br>      title: &#39;Reactive Flutter&#39;,<br>      theme: ThemeData(<br>        primarySwatch: Colors.indigo,<br>        canvasColor: Colors.transparent<br>      ),<br>      <em>//Our only screen/page we have<br>      </em>home: HomePage(title: &#39;My Todo List&#39;),<br>    );<br>  }<br>}</pre><p>This the conclusion of this article, I hope this is somehow clarified some of these BLoC design pattern concept for Flutter project, please share your feedback or questions and I will try to do my best to reply back them.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b71e2434f692" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Idiomatic Android Architecture Components with Koin]]></title>
            <link>https://vaygeth.medium.com/idiomatic-android-architecture-components-with-koin-51ecc648e646?source=rss-37cce710294------2</link>
            <guid isPermaLink="false">https://medium.com/p/51ecc648e646</guid>
            <category><![CDATA[architecture-components]]></category>
            <category><![CDATA[koin]]></category>
            <category><![CDATA[dagger-2]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Vaygeth (Abdulmohsen)]]></dc:creator>
            <pubDate>Sun, 06 May 2018 09:23:21 GMT</pubDate>
            <atom:updated>2018-05-06T09:23:21.708Z</atom:updated>
            <content:encoded><![CDATA[<p>This post aims to focus on demonstrating the use of Architecture Components with Koin dependency injection in simple &amp; idiomatic way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1_J8doSg4SzQQd_p7DXTig.png" /><figcaption><a href="https://insert-koin.io/">https://insert-koin.io/</a> &amp; <a href="https://github.com/Ekito/koin">https://github.com/Ekito/koin</a></figcaption></figure><p><strong>Why this post?</strong></p><p>As Android developer, I always avoid stacking up huge dependencies and libraries in any of my development projects, because I noticed myself struggling setting up and debugging the errors of these libraries rather than focusing on developing &amp; delivering the project. This happens often when I’m new to certain frameworks, therefore I only absolutely use them when I estimate this will be the beneficial approach for my use-cases. Common practices in Android community is often follows the approach of employing <a href="https://github.com/google/dagger"><strong>Dagger 2</strong></a> for <a href="https://en.wikipedia.org/wiki/Dependency_injection"><strong>dependency injection</strong></a><strong>.</strong> Dagger 2 approach is often discouraging for new learners (and me when I started learning Dagger 2 concepts). So in this <a href="https://github.com/vaygeth89/Android-ArchitectureCompKoin-Company"><strong>code samples</strong></a><strong> </strong>I implemented a simple way to handle Android Architecture Components in <a href="https://kotlinlang.org/"><strong>Kotlin </strong></a>with support of <a href="https://github.com/Ekito/koin">Koin</a> dependency injection.</p><p><strong>More reason I prefer Koin over Dagger 2?</strong></p><p>As clarified in previous section that I always intend to minimize complex libraries or advanced techniques where it can be achieved in cleaner &amp; simplistic approach, Koin offers that in place of Dagger 2 by doing the full implementation using Kotlin code without annotation or framework constraint. Unlike Koin, Dagger 2 heavily uses annotations and abstractions which makes code implementations complex and neither intuitive (at least in my opinion) by creating many interfaces &amp; abstract classes for small projects.</p><p><strong>What does the app do?</strong></p><p>It’s a Company app that displays all it’s employees names with their age in a recycle-view list, where you can add one employee into database or delete the whole employees records on database via floating action buttons.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/342/1*yyFNRecg6p8qEcdO8FTYUA.png" /><figcaption><a href="https://github.com/vaygeth89/Android-ArchitectureCompKoin-Company">https://github.com/vaygeth89/Android-ArchitectureCompKoin-Company</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51ecc648e646" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>