<?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 Usama Hafeez on Medium]]></title>
        <description><![CDATA[Stories by Usama Hafeez on Medium]]></description>
        <link>https://medium.com/@usamahafeez0?source=rss-69f18797ec7d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dmbNkD5D-u45r44go_cf0g.png</url>
            <title>Stories by Usama Hafeez on Medium</title>
            <link>https://medium.com/@usamahafeez0?source=rss-69f18797ec7d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 10:54:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@usamahafeez0/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[Streaming UI with Suspense in NextJS]]></title>
            <link>https://medium.com/@usamahafeez0/streaming-ui-with-suspense-in-nextjs-e30ac1466dbc?source=rss-69f18797ec7d------2</link>
            <guid isPermaLink="false">https://medium.com/p/e30ac1466dbc</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[react-suspense]]></category>
            <category><![CDATA[server-side-rendering]]></category>
            <dc:creator><![CDATA[Usama Hafeez]]></dc:creator>
            <pubDate>Tue, 23 May 2023 17:27:26 GMT</pubDate>
            <atom:updated>2023-05-23T17:27:26.103Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3xzwMcCqxj_H0grXMwySog.png" /><figcaption><strong>AI image again!</strong></figcaption></figure><p>Hello everyone! In this blog post, we are going to discuss about Streaming UI using Suspense, its benefits and its effect on SEO.</p><h3>Contents</h3><ol><li>Demo of created app</li><li>Components involved - Suspense</li><li>How does streaming work</li><li>Code explanation</li><li>Main idea and benefits</li><li>Impact on SEO</li></ol><h3>Demo</h3><p>Lets start by looking at what we have created for understanding the things we need to understand. A simple webpage which loads video from a provided URL, the important thing to notice here is the suggested videos and comments, they work like they are “streamed” response meaning, the whole page is not built at once rather it gets built progressively as we keep getting data from the server.</p><p>In our case, first the video starts playing, then 2 seconds later (2 second setTimer to mimic data fetching) suggested videos are fetched from the server and displayed and then after some time (4 seconds or 2 more seconds after suggested videos get loaded) the comments load and show up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*WaAkaVL0l9235-8yFmLXHg.gif" /><figcaption>Streaming server rendering</figcaption></figure><h3>Components involved — Suspense</h3><p>So, what’s suspense? Suspense is a React feature that allows us to handle async operations in a declarative and more readable way.</p><p>We can wrap components with async dependencies with &lt;Suspense&gt; component and provide a fallback UI. This fallback UI is displayed while the async operation is being completed. It simplifies handling states for showing loading state.</p><h3>How does Streaming work</h3><p>Nextjs supports sever side rendering, which in short works by fetching the data required by the page on the server, renders then html on server and then sends all that to the client.</p><p>Data fetching is blocking which means we need to fetch data for a page before we can render and hyderate it on the client.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*UtKIwOdKDn_CiJYtYdHj7A.png" /><figcaption>How does server side rendering work (<a href="https://nextjs.org/docs/app/building-your-application/routing/loading-ui-and-streaming">source</a>)</figcaption></figure><p>But, React is great candidate for “Streaming” because its based on components and each component can be considered a separate page, hence a page (component) goes through the SSR (server side rendering) steps and is shown on the client side while other components which are also going to be displayed in the same parent page are still fetching the data. This enables progressively buidling the UI.</p><h3>Code Explanation</h3><p>This is our SuggestedVideos component that fetches the videos (mocking with setTimeout).</p><pre>async function getSuggestedVideos() {<br>  await new Promise((resolve) =&gt; setTimeout(resolve, 2000));<br>  return Array.from({ length: 10 }, (_, index) =&gt; &quot;Video&quot;);<br>}<br><br>export default async function SuggestedVideos() {<br>  const suggestedVideos = await getSuggestedVideos();<br>  return suggestedVideos.map((video, index) =&gt; {<br>    return (<br>      &lt;div<br>        className={`flex flex-row items-center ${<br>          index != 0 ? &quot;p-4&quot; : &quot;px-4 pb-4&quot;<br>        }`}<br>      &gt;<br>        &lt;div className=&quot;rounded bg-slate-700 w-44 h-20&quot;&gt;&lt;/div&gt;<br>        &lt;p className=&quot;p-2&quot;&gt;Video {index + 1}&lt;/p&gt;<br>      &lt;/div&gt;<br>    );<br>  });<br>}</pre><p>This is our Comments component that fetches the comments (mocking with setTimeout).</p><pre>async function getComments() {<br>  await new Promise((resolve) =&gt; setTimeout(resolve, 4000));<br>  return Array.from({ length: 20 }, (_, index) =&gt; &quot;Comment&quot;);<br>}<br><br>export default async function Comments() {<br>  const comments = await getComments();<br>  return comments.map((comment, index) =&gt; {<br>    return &lt;p className=&quot;p-2&quot;&gt;Comment {index + 1}&lt;/p&gt;;<br>  });<br>}</pre><p>This is our Homepage component that shows the video and wraps the comments and suggested videos in &lt;Suspense&gt;</p><pre>export default function Homepage() {<br>  return (<br>    &lt;div className=&quot;flex flex-row justify-between px-20 py-10&quot;&gt;<br>      &lt;div className=&quot;pr-6 flex flex-col flex-grow-2 w-2/3&quot;&gt;<br>        &lt;div className=&quot;flex flex-col&quot;&gt;<br>          &lt;VideoPlayer&gt;&lt;/VideoPlayer&gt;<br>        &lt;/div&gt;<br>        &lt;div className=&quot;pt-6&quot;&gt;<br>          // Suspense here<br>          &lt;Suspense fallback={&lt;p&gt;Loading suggested videos...&lt;/p&gt;}&gt; <br>            &lt;Comments&gt;&lt;/Comments&gt; // <br>          &lt;/Suspense&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>      &lt;div className=&quot;flex-grow&quot;&gt;<br>        // Suspense here<br>        &lt;Suspense fallback={&lt;p&gt;Loading suggested videos...&lt;/p&gt;}&gt;<br>          &lt;SuggestedVideos&gt;&lt;/SuggestedVideos&gt;<br>        &lt;/Suspense&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>As in the above code, we are using &lt;Suspense&gt; to wrap our comments and Suggested videos components both of which fetch data asynchronously to render it.</p><p><strong>full code here: </strong><a href="https://github.com/UsamaHafeez0/streaming-suspense-and-seo"><strong>github</strong></a></p><h3>Main idea and benefits</h3><p>The fallback is supposed to be a meaningful UI (unlike my example here_ or it can be part of some state, for example it can be the name of Video that is currently loading.</p><p>So, the main idea behind this simple thing is to improve the <strong>User experience </strong>and improve the <strong>perceived loading performance</strong>. Its useful in cases where there is some time taking request that can prevent UI from being rendered.</p><h3>Impact on SEO</h3><p>Streaming doesn’t effect the SEO in any negative way.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e30ac1466dbc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is Flutte]]></title>
            <link>https://medium.com/@usamahafeez0/what-is-flutte-f17462b2347e?source=rss-69f18797ec7d------2</link>
            <guid isPermaLink="false">https://medium.com/p/f17462b2347e</guid>
            <category><![CDATA[flutter-bloc]]></category>
            <category><![CDATA[bloc]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Usama Hafeez]]></dc:creator>
            <pubDate>Thu, 06 Apr 2023 12:19:09 GMT</pubDate>
            <atom:updated>2023-05-14T19:06:15.602Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is Flutter Bloc (Part 1)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vmn37-fTibORJMQ66uBVjQ.png" /></figure><h3>Content:</h3><ol><li>State Management in Flutter</li><li>What is Bloc and Cubit</li><li>Flutter Bloc Widgets</li><li>Bloc Architecture</li><li>Implementing Bloc in Flutter</li></ol><p><strong>Please read official documentation: </strong><a href="https://bloclibrary.dev/">Official Documentation</a>.</p><h3>State Management in Flutter</h3><p>State management is the process of updating and managing the state of an application. State management is a necessity for bigger and complex projects because without it, it becomes very difficult to manage the code and the code is prone to bugs.</p><p>Without state management we would need to manually pass the data between screens and update the data manually as well which can become problematic as the app grows.</p><p>For example, if you’re making an Ecommerce application and there are multiple screens where you need to show and manipulate products data like product list, product details or cart page, then we would need to pass the data (state) manually between screens and update and trigger updates manually as well.</p><p>Also, in Flutter you might end up degrading applications performance if you’re not careful with the setState method, while this is also true for any state management technique but they make it easier to apply optimizations along with other very important benefits.</p><p><strong>Benefits of State management</strong></p><p><strong>Increased Performance and Granular Control: </strong>State management tools provide granular control over the state of application. For example, with Flutter Bloc we can context.select in Bloc allows you to listen for changes in even a smaller part of the state. And they also increase the app’s performance by reducing the number of rebuilds.</p><p><strong>Separation of concerns: </strong>State management tools help to separate the business logic from UI, this separation of concerns allows for better code readability, code maintainability and also makes testing easier.</p><p><strong>Scaling: </strong>State management makes scaling the application easier as the application grows in size and complexity. By providing structured and efficient ways to manage application’s state state management tools allow for code maintainability even when the application grows.</p><p><strong>Code Reusability: </strong>State management makes it easier to reuse code. By separating the UI from business logic, state management allows for reusing the state management code across widgets and screens.</p><h3>What is Bloc and Cubit</h3><p>Flutter Bloc is a state management pattern. The purpose of Bloc is to separate the user interface (presentation) from the underlying logic of the application (business logic), making it easier to test and reuse the code.</p><p><strong>Bloc</strong></p><p>When working with Bloc pattern we have events, state and bloc. <strong>Events</strong> are the actions that a user can perform like clicking a button. <strong>State </strong>is data that can change over time and affects the appearance of application like the value of counter in counter app. <strong>Bloc </strong>is where we put the business logic, we map events to new states in Bloc. Events go into the bloc and states come out of it. Bloc uses streams to emit states.</p><p>In Bloc, we fire events from the UI when the user interacts with the screen, events go into Bloc and we map events to new states in the bloc, depending on the event a new state is emitted from the Bloc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*I_P7iPXmfwcg3wTRjI_R1w.png" /><figcaption>Bloc</figcaption></figure><p>For example, When we swipe down the screen to refresh the screen we will add a new event to the bloc, let’s name the event “RefreshScreen” or something and then inside the Bloc we will fetch the latest data from API on receiving the RefreshScreen event and emit the new state using the latest data. State can be a list of recipes here for example which would contain the latest information from the API.</p><p><strong>Cubit</strong></p><p>Cubit is also used for state management and it is very similar to Bloc except it uses functions to emit new states instead of events.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/1*7KdVADNrEZq8sihcvYxoJA.png" /><figcaption>Cubit</figcaption></figure><p><strong>Bloc vs Cubit:</strong></p><p>Bloc and Cubit both can be used side by side in an application but they have a few differences:</p><ol><li>Cubit uses functions to emit state whereas Bloc uses events.</li><li>Cubit is simpler as compared to Bloc and relatively easy to understand.</li><li>Cubit has limited capabilities compared to Bloc and may not be suitable for larger and complex applications.</li></ol><h3>Flutter Bloc Widgets</h3><p>To implement the Bloc pattern in Flutter, the “flutter_bloc” package provides many widgets.</p><p>We will go through each of them and discuss their uses.</p><p><strong>BlocBuilder</strong></p><p>BlocBuilder requires a Bloc and a builder function. BlocBuilder builds UI in response to new state. If we omit the Bloc, then it automatically looks up using BlocBuilder and the current BuildContext.</p><p>We can optionally provide buildWhen which takes previous state and new state. BlocBuilder will rebuild only if buildWhen returns true.</p><pre>BlocBuilder&lt;BlocA, BlocAState&gt;(<br>  buildWhen: (previousState, state) {<br>    // return true/false to determine whether or not<br>    // to rebuild the widget with state<br>  },<br>  builder: (context, state) {<br>    // return widget here based on BlocA&#39;s state<br>  }<br>)</pre><p><strong>BlocSelector</strong></p><p>BlocSelector is used to filter updates by selecting a new value from the Bloc current state. The update doesn’t occur if the selected value doesn’t change which prevents unnecessary rebuilds.</p><pre>BlocSelector&lt;BlocA, BlocAState, SelectedState&gt;(<br>  selector: (state) {<br>    // return selected state based on the provided state.<br>  },<br>  builder: (context, state) {<br>    // return widget here based on the selected state.<br>  },<br>)</pre><p><strong>BlocProvider</strong></p><p>BlocProvider provides the Bloc to Widget’s children via BlocProvider.of(context). It is used as a dependency injection widget to provide a single instance of Bloc to children widgets. BlocProvider should be used to create Bloc which will be provided to subtree, since it creates the Bloc, it handles automatically closing the Bloc as well.</p><p>By default BlocProvider is created lazily which means it will be created once it’s first looked up using BlocProvider.of&lt;BlocA&gt;(context). This behaviour can be overridden by setting the lazy attribute to false.</p><pre>BlocProvider(<br>  create: (BuildContext context) =&gt; BlocA(),<br>  child: ChildA(),<br>);</pre><p>BlocProvider can be used to provide existing Bloc to another subtree.</p><pre>BlocProvider.value(<br>  value: BlocProvider.of&lt;BlocA&gt;(context),<br>  child: ScreenA(),<br>);</pre><p><strong>MultiBlocProvider</strong></p><p>MultiBlocProvider is similar to BlocProvider, it’s used to provide multiple Blocs to the subtree. It’s like merging multiple BlocProvider into one widget. It improves readability and eliminates the need for merging.</p><pre>MultiBlocProvider(<br>  providers: [<br>    BlocProvider&lt;BlocA&gt;(<br>      create: (BuildContext context) =&gt; BlocA(),<br>    ),<br>    BlocProvider&lt;BlocB&gt;(<br>      create: (BuildContext context) =&gt; BlocB(),<br>    ),<br>    BlocProvider&lt;BlocC&gt;(<br>      create: (BuildContext context) =&gt; BlocC(),<br>    ),<br>  ],<br>  child: ChildA(),<br>  )</pre><p><strong>BlocListener</strong></p><p>BlocListener takes a BlocWidgetListener and a Bloc. It invokes the listener in response to state changes in Bloc. BlocListener runs only once for a state change. It should be used for functionality that needs to run only once per state change like navigation or showing a snackbar etc. If the Bloc is omitted it looks up using BlocProvider and the current BuildContext.</p><pre>BlocListener&lt;BlocA, BlocAState&gt;(<br>  listener: (context, state) {<br>    // do stuff here based on BlocA&#39;s state<br>  },<br>  child: Container(),<br>)</pre><p>We can further fine grain the control using listenWhen, the listener will only run if listenWhen returns true.</p><pre>BlocListener&lt;BlocA, BlocAState&gt;(<br>  listenWhen: (previousState, state) {<br>    // return true/false to determine whether or not<br>    // to call listener with state<br>  },<br>  listener: (context, state) {<br>    // do stuff here based on BlocA&#39;s state<br>  },<br>  child: Container(),<br>)</pre><p><strong>MultiBlocListener</strong></p><p>MultiBlocListener combines multiple BlocListener into a single widget. It improves readability and removes the need for nesting.</p><pre>MultiBlocListener(<br>  listeners: [<br>    BlocListener&lt;BlocA, BlocAState&gt;(<br>      listener: (context, state) {},<br>    ),<br>    BlocListener&lt;BlocB, BlocBState&gt;(<br>      listener: (context, state) {},<br>    ),<br>    BlocListener&lt;BlocC, BlocCState&gt;(<br>      listener: (context, state) {},<br>    ),<br>  ],<br>  child: ChildA(),<br>)</pre><p><strong>BlocConsumer</strong></p><p>BlocConsumer exposes a listener and builder to react to new states. BlocConsumer is analogous to nested BlocListener and BlocBuilder but it reduces the boilerplate code needed.</p><p>It provides optional buildWhen and listenWhen just as BlocBuilder and BlocListener does.</p><pre>BlocConsumer&lt;BlocA, BlocAState&gt;(<br>  listenWhen: (previous, current) {<br>    // return true/false to determine whether or not<br>    // to invoke listener with state<br>  },<br>  listener: (context, state) {<br>    // do stuff here based on BlocA&#39;s state<br>  },<br>  buildWhen: (previous, current) {<br>    // return true/false to determine whether or not<br>    // to rebuild the widget with state<br>  },<br>  builder: (context, state) {<br>    // return widget here based on BlocA&#39;s state<br>  }<br>)</pre><p><strong>RepositoryProvider</strong></p><p>RepositoryProvider widget is used to provide a Repository to a widget’s children via RepositoryProvider.of(context). It is used as a dependency Injection widget to provide a single instance of repository to widgets in a subtree.</p><pre>RepositoryProvider(<br>  create: (context) =&gt; RepositoryA(),<br>  child: ChildA(),<br>);</pre><p>Then in ChildA we can access repository using:</p><p>RepositoryProvider.of&lt;RepositoryA&gt;(context)</p><p><strong>MultiRepositoryProvider</strong></p><p>MultiRepositoryProvider merges multiple RepositoryProvider widgets into one. It improves readability and eliminates the need to nest multiple RepositoryProvider widgets.</p><pre>MultiRepositoryProvider(<br>  providers: [<br>    RepositoryProvider&lt;RepositoryA&gt;(<br>      create: (context) =&gt; RepositoryA(),<br>    ),<br>    RepositoryProvider&lt;RepositoryB&gt;(<br>      create: (context) =&gt; RepositoryB(),<br>    ),<br>    RepositoryProvider&lt;RepositoryC&gt;(<br>      create: (context) =&gt; RepositoryC(),<br>    ),<br>  ],<br>  child: ChildA(),<br>)</pre><p><strong>Extension methods</strong></p><p>Extension methods were introduced in Dart 2.7, extensions are used to extend functionality of a library without sub-classing it.</p><p>“flutter_bloc” package exposes following extension methods:</p><p><strong>Context.read</strong></p><p>Context.read is functionally equivalent to BlocProvider.of&lt;T&gt;(context). It’s mostly used to retrieve a Bloc to add events to it in onPressed callback.</p><p>context.read&lt;CounterBloc&gt;().add(CounterIncrementPressed())</p><p><strong>context.watch</strong></p><p>context.read is functionally equivalent to BlocProvider.of&lt;T&gt;(context, listen: true). It listens to changes on the instance.</p><p>context.watch is only accessible within the build method of a StatelessWidget or State class and using context.watch at the root of the build method will result in the entire widget being rebuilt when the bloc state changes.</p><p><strong>context.select</strong></p><p>context.select, context.select&lt;T, R&gt;(R function(T value)) is used to listen to changes just like context.watch but it listens to changes in a smaller part of state.</p><pre>Widget build(BuildContext context) {<br>  final name = context.select((ProfileBloc bloc) =&gt; bloc.state.name);<br>  return Text(name);<br>}</pre><h3>Bloc Architecture</h3><p>Bloc works by using events, states and Bloc. The bloc library allow us to divide the application in 3 layers where each layer has its own responsibility:</p><ol><li>Application Layer</li><li>Business Logic Layer</li><li>Data Layer</li></ol><p><strong>Data Layer:</strong></p><p>The data layer is responsible for retrieving and manipulating data from one or more data sources.</p><p>The Data Layer is further divided into two parts:</p><ol><li>Data Provider</li><li>Repository</li></ol><p><strong>Data Provider</strong></p><p>The purpose of Data Provider is to provide raw data, it should be generic and versatile.</p><p><strong>Repository</strong></p><p>Repository acts as a wrapper around one or multiple data providers. The Bloc communicates with the Repository.</p><p><strong>Business Logic Layer</strong></p><p>The business logic layer is responsible for responding to inputs from the UI with new states. This can depend upon one or multiple Repositories to get the data needed to build the app state.</p><p><strong>Presentation Layer</strong></p><p>The Presentation layer is responsible for rendering itself based on one or more then one bloc.</p><p><strong>How does all this connect</strong></p><p>Let’s take an example to see how this all works together. For example, the user clicks on the Login Button which is rendered by the presentation layer in the Login Page. The login page depends on AuthBloc, upon click, an event is fired which is handled by the AuthBloc, the AuthBloc will now pass the login request along with the username and password to the repository. Suppose we are using Firebase auth, the Auth Repository depends on Firebase data provider and the repo will call the corresponding data provider to make the API call which would then call the Firebase API.</p><p>By structuring our applications in this manner we can facilitate testability and reusability. For example, the Firebase Data Provider can be turned into a package and used with other applications as well.</p><h3>Implementing Bloc in Flutter</h3><p><a href="https://medium.com/@work.usamahafeez/how-to-use-flutter-bloc-part-2-668c26d2ac0b">Part 2.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f17462b2347e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to use Flutter Bloc (part 2)]]></title>
            <link>https://medium.com/@usamahafeez0/how-to-use-flutter-bloc-part-2-668c26d2ac0b?source=rss-69f18797ec7d------2</link>
            <guid isPermaLink="false">https://medium.com/p/668c26d2ac0b</guid>
            <category><![CDATA[bloc]]></category>
            <category><![CDATA[flutter-bloc]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Usama Hafeez]]></dc:creator>
            <pubDate>Thu, 06 Apr 2023 12:16:00 GMT</pubDate>
            <atom:updated>2023-04-06T12:22:32.212Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aggtB8pXTLhoxZ3HNy0R9A.jpeg" /></figure><p>AI Image cuz why not?</p><p><a href="https://medium.com/@work.usamahafeez/what-is-flutte-f17462b2347e"><strong>Part 1 is here.</strong></a></p><h3>Hi</h3><p>Hello readers, we are going to make a simple application to see how the Bloc works. It’s a simple application which uses a basic age guessing API, we pass in the name as a query parameter and it guesses your age based on the entered name.</p><p>API URL is <a href="https://api.agify.io/?name=NameXYZ">https://api.agify.io/?name=NameXYZ</a></p><p>I’m not going to go into much details about creating a package for the repository and all the detailed stuff, instead I’m going to create a simple class named GuessAgeRepo and provide it to the tree using RepositoryProvider.</p><h3>App</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/192/1*lGJuMn0muKB81xWF6c5o6Q.gif" /><figcaption>Guess Age application</figcaption></figure><h3><strong>File Structure</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/363/1*V2Wh8xqWRH0lAXjJ-SdWQA.png" /><figcaption>File structure</figcaption></figure><p><strong>Features: </strong>Features directory will contain presentation and business logic layer related stuff (UI, widgets, Bloc etc) in it and each feature will have its own directory inside of features directory like one can have login, signup, homepage and so on as features.</p><p>In our case we have only 1 feature named Guess Age, so we have only 1 nested directory inside of features directory. We have the guess_age_page file which contains the UI and Bloc files, which we will go through after this.</p><p><strong>Repo:</strong><em> I’m not following proper way here which would be to create a data provider layer which would call http methods and our repo will use that layer to call the get method but I’m just going without data provider for the sake of this guide and putting repositories here (</em><em>GuessAgeRepo). But you can read the documentation and follow from there.</em></p><p>Then we have the <strong>main.dart</strong> file and <strong>form_submission_status</strong> file. We can make a directory named <strong>core</strong> and put the form submission file in there as we would put all the files that are common in our project inside core directory, for example application Bloc or widgets that multiple screens use.</p><h3>Repo</h3><pre>class GuessAgeRepo {<br>  final String guessAgeAPIURL = &#39;https://api.agify.io/?name=&#39;;<br><br>  Future&lt;int&gt; guessAge({required String name}) async {<br>    String APIURL = guessAgeAPIURL + name;<br>    log(APIURL);<br>    var url = Uri.parse(APIURL);<br>    try {<br>      var response = await http.get(url);<br>      var data = jsonDecode(response.body);<br>      log(&#39;Data fetched:  ${data.toString()}&#39;);<br><br>      if(data[&#39;age&#39;] != null) {<br>        return data[&#39;age&#39;];<br>      }<br>      else{<br>        throw Exception(&#39;Error guessing age&#39;);<br>      }<br>    }<br>    catch (e){<br>      log(&#39;Error fetching data: ${e.toString()}&#39;);<br>      rethrow;<br>    }<br>  }<br>}</pre><p>The Repository has the url of API and a simple function which calls the api with the provided name.</p><p>We are doing a bit of exception handling here to see if something went wrong in the API call like api returning null for age or no internet connection. We would throw errors here and catch them inside the Bloc to do our business logic and display snackbar for failures. I’m using generic messages on exceptions here but they are supposed to represent what actually went wrong.</p><h3>Bloc</h3><blockquote><strong>Events</strong></blockquote><pre>abstract class GuessAgeEvent{}<br><br>class UpdateName extends GuessAgeEvent{<br>  String name;<br><br>  UpdateName({required this.name});<br>}<br><br>class GuessMyAge extends GuessAgeEvent{}</pre><p>We have only 2 events.</p><p><strong>UpdateName </strong>has a String name which we pass when the user edits the input name, it goes to Bloc and the Bloc emits a new state with the updated name.</p><p><strong>GuessMyAge </strong>is when a user clicks on the button to get a guess about their age.</p><blockquote><strong>State</strong></blockquote><pre>abstract class GuessAgeState extends Equatable{}<br><br>class GuessAgeErrorState extends GuessAgeState {<br>  final String error;<br><br>  GuessAgeErrorState({required this.error});<br><br>  @override<br>  List&lt;Object?&gt; get props =&gt; [error];<br>}<br><br>class GuessAge extends GuessAgeState {<br>  final String name;<br>  final int? age;<br>  final FormSubmissionState status;<br><br>  GuessAge({required this.status, this.name = &#39;&#39;, this.age});<br><br>  GuessAge copyWith({<br>    FormSubmissionState? status,<br>    String? name,<br>    int? age,<br>  }) {<br>    return GuessAge(<br>      status: status?? this.status,<br>      name: name ?? this.name,<br>      age: age ?? this.age,<br>    );<br>  }<br><br>  @override<br>  List&lt;Object?&gt; get props =&gt; [status, name, age];<br>}</pre><p>We are going to use polymorphism to represent a couple of states here, Error State and the Normal State.</p><p>Whenever the API fails we emit an Error state to display the snackbar. Error state class has a String error which we can use to display the error.</p><p>If the API doesn’t throw an error or we haven’t called the API yet, we are using GuessAge state where we will show the guessed age of the entered user. It has a name which the user will enter, age which will be guessed and returned by API and SubmissionFromState which we will use to display progress indicator while awaiting for results from API. We have a copyWith method to update the variables as needed.</p><p>Our state classes are extending Equatable so we can define what to compare when we want to check if two states are equal or not in order to optimise the rebuilds.</p><blockquote><strong>Bloc</strong></blockquote><pre>class GuessAgeBloc extends Bloc&lt;GuessAgeEvent, GuessAgeState&gt;{<br>  GuessAgeBloc({required this.guessAgeRepo}) : super(GuessAge(status: InitialFormSubmissionState())){<br>    on&lt;UpdateName&gt;(_updateName);<br>    on&lt;GuessMyAge&gt;(_guessMyAge);<br>  }<br><br>  GuessAgeRepo guessAgeRepo;<br><br>  void _updateName(UpdateName event, Emitter&lt;GuessAgeState&gt; emit) {<br>    if(state is GuessAge){<br>      emit((state as GuessAge).copyWith(name: event.name));<br>    }<br>  }<br><br>  FutureOr&lt;void&gt; _guessMyAge(GuessMyAge event, Emitter&lt;GuessAgeState&gt; emit) async {<br>    if(state is GuessAge) {<br>      try {<br>        String name = (state as GuessAge).name;<br><br>        emit((state as GuessAge).copyWith(status: SubmittingFormSubmissionState()));<br><br>        int age = await guessAgeRepo.guessAge(name: name);<br>        emit((state as GuessAge).copyWith(name: &#39;&#39;, age: age, status: InitialFormSubmissionState()));<br>      }<br>      catch (e){<br>          emit(GuessAgeErrorState(error: e.toString()));<br>          emit(GuessAge(name: &#39;&#39;, status: InitialFormSubmissionState()));<br>      }<br>    }<br>  }<br>}</pre><p>Bloc class has GuessAgeRepo which is passed in from the constructor, the reason for passing it in constructor instead of initialising it inside is so that we have the ability to mock the Repo during testing. We can pass a mock repository in the constructor to Bloc when testing Bloc.</p><p>We have two methods inside Bloc, one to handle the UpdateName event and another for calling the API on button click (GuessMyAge Event).</p><p><strong>updateName</strong> simply takes the new name provided in the event class and updates the state with the new name.</p><p><strong>guessMyAge </strong>method calls the API inside the try catch clause. Before awaiting for the API call response we change the FormSubmissionState to Submitting state so that we can represent the loading or awaiting inside the UI. If the API call is successful we update the age variable in state class and if not we change the state to Error state and show snackbar in the UI that some error has occurred.</p><blockquote><strong>FormSubmissionState</strong></blockquote><pre>abstract class FormSubmissionState {}<br><br>class InitialFormSubmissionState extends FormSubmissionState{}<br><br>class SubmittingFormSubmissionState extends FormSubmissionState{}</pre><p>This will represent if the form is submitted and we are awaiting response and show a circular progress indicator based on this.</p><p>Couple of reasons why we have not made a variable for loading or something inside the state or a class like we have for Error state is <strong>reusability</strong> and to actually <strong>reduce the number of rebuilds</strong> as we can use BlocSelector on this which we will see in the UI.</p><h3>UI</h3><pre>class GuessAgePage extends StatefulWidget {<br>  const GuessAgePage({Key? key}) : super(key: key);<br><br>  @override<br>  State&lt;GuessAgePage&gt; createState() =&gt; _GuessAgePageState();<br>}<br><br>class _GuessAgePageState extends State&lt;GuessAgePage&gt; {<br>  final TextEditingController nameController = TextEditingController();<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        title: const Text(&#39;Guess My Age&#39;),<br>      ),<br>      body: BlocListener&lt;GuessAgeBloc, GuessAgeState&gt;(<br>        listener: (context, state) {<br>          if (state is GuessAgeErrorState) {<br>            ScaffoldMessenger.of(context).showSnackBar(<br>              SnackBar(<br>                backgroundColor: Colors.redAccent,<br>                content: Text(state.error),<br>              ),<br>            );<br>          }<br>        },<br>        child: ListView(<br>          padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 20),<br>          children: [<br>            const Text(&#39;Enter you name&#39;),<br>            const SizedBox(height: 10),<br>            TextField(<br>              controller: nameController,<br>              decoration: const InputDecoration(border: OutlineInputBorder()),<br>              onChanged: (name) =&gt;<br>                  context.read&lt;GuessAgeBloc&gt;().add(UpdateName(name: name)),<br>            ),<br>            const SizedBox(height: 40),<br>            BlocSelector&lt;GuessAgeBloc, GuessAgeState, FormSubmissionState&gt;(<br>              selector: (state) {<br>                if(state is GuessAge){<br>                  return (state).status;<br>                }<br>                else{<br>                  return InitialFormSubmissionState();<br>                }<br>              },<br>              builder: (context, status) {<br>                return SizedBox(<br>                  height: 50,<br>                  child: status is SubmittingFormSubmissionState?<br>                      ? const Center(<br>                          child: CircularProgressIndicator(),<br>                        )<br>                      : ElevatedButton(<br>                          onPressed: () {<br>                            context.read&lt;GuessAgeBloc&gt;().add(GuessMyAge());<br>                            nameController.clear();<br>                          },<br>                          child: const Text(&#39;Guess My Age&#39;),<br>                        ),<br>                );<br>              },<br>            ),<br>            const SizedBox(height: 20),<br>            BlocSelector&lt;GuessAgeBloc, GuessAgeState, int?&gt;(<br>              selector: (state) {<br>                if (state is GuessAge &amp;&amp; state.age != null) {<br>                  return state.age;<br>                }<br>                return null;<br>              },<br>              builder: (context, age) {<br>                return age != null<br>                    ? Text(&#39;Your guessed age is: $age&#39;)<br>                    : const SizedBox();<br>              },<br>            ),<br>          ],<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><pre> BlocListener&lt;GuessAgeBloc, GuessAgeState&gt;(<br>        listener: (context, state) {<br>          if (state is GuessAgeErrorState) {<br>            ScaffoldMessenger.of(context).showSnackBar(<br>              SnackBar(<br>                backgroundColor: Colors.redAccent,<br>                content: Text(state.error),<br>              ),<br>            );<br>          }<br>        },</pre><p>We are using BlocListener at the top to check for error states, as instructed by the documentation. Use BlocListener for doing things that need to be done only once like navigation and showing snackbar etc. We check if the state is Error State then we show the error message which the error state class contains (which was returned by repo and bloc).</p><pre> <br>TextField(<br>  controller: nameController,<br>  decoration: const InputDecoration(border: OutlineInputBorder()),<br>  onChanged: (name) =&gt;<br>      context.read&lt;GuessAgeBloc&gt;().add(UpdateName(name: name)),<br>),</pre><p>We are adding an UpdateName event to update the name in state class.</p><pre> BlocSelector&lt;GuessAgeBloc, GuessAgeState, FormSubmissionState&gt;(<br>....<br>)</pre><p>We are using BlocSelector to decide whether to show the submit button or progress indicator based on FormSubmissionState. BlocSelector will only run if the FormSubmissionState changes and this prevents unnecessary rebuilds.</p><pre>BlocSelector&lt;GuessAgeBloc, GuessAgeState, int?&gt;(<br>...<br>)</pre><p>We are using another BlocSelector to display the guessed age, we could have used BlocBuilder or something else here but the benefit of using BlocSelector here is again to prevent unnecessary rebuilds. This part will only get rebuilt when the age changes.</p><h3>Main.dart</h3><pre>void main() {<br>  runApp(const MyApp());<br>}<br><br>class MyApp extends StatelessWidget {<br>  const MyApp({Key? key}) : super(key: key);<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return MaterialApp(<br>      home: RepositoryProvider(<br>        create: (BuildContext context) =&gt; GuessAgeRepo(),<br>        child: BlocProvider(<br>            create: (BuildContext context) =&gt; GuessAgeBloc(<br>                  guessAgeRepo: context.read&lt;GuessAgeRepo&gt;(),<br>                ),<br>            child: const GuessAgePage()),<br>      ),<br>    );<br>  }<br>}</pre><p>In the main file, we are using RepositoryProvider to provide the GuessAgeRepo and BlocProvider to provide the GuessAgeBloc to the subtree.</p><h3>The End</h3><p>As from the above implementation, we have seen that using Bloc we can have reusability, maintainability as the code is not messy or anything and even if the application grows our GuessAge part is not going to get messy. It will also provide easiness in testing because we have separated out the code into many layers and decoupled the code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=668c26d2ac0b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>