<?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 Ali Assi on Medium]]></title>
        <description><![CDATA[Stories by Ali Assi on Medium]]></description>
        <link>https://medium.com/@ali_assi?source=rss-f0b80b132721------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*xwAmCFDhffbSIAoOZdVtgQ.jpeg</url>
            <title>Stories by Ali Assi on Medium</title>
            <link>https://medium.com/@ali_assi?source=rss-f0b80b132721------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 05:29:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ali_assi/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[Flutter BLoC State Management. Unit, Widget & Integration Testing]]></title>
            <link>https://medium.com/@ali_assi/flutter-bloc-state-management-unit-widget-integration-testing-ac6a33e5f8a9?source=rss-f0b80b132721------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac6a33e5f8a9</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[bloc]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[automated-testing]]></category>
            <category><![CDATA[integration-testing]]></category>
            <dc:creator><![CDATA[Ali Assi]]></dc:creator>
            <pubDate>Sun, 15 Sep 2024 10:49:10 GMT</pubDate>
            <atom:updated>2024-09-20T09:47:22.970Z</atom:updated>
            <content:encoded><![CDATA[<p>In our <a href="https://medium.com/@ali_assi/mastering-flutter-state-management-with-the-bloc-pattern-2b3fc10ed3be">previous article</a>, we explored the fundamentals of bloc state management and developed a bloc-based application to fetch lists of dogs and cats, incorporating Firebase authentication. This provided a solid foundation for understanding bloc principles and their practical application.</p><p>Building upon that knowledge, this article delves deeper into advanced Bloc techniques and testing strategies. We will examine how to handle complex state management scenarios, implement error handling and loading indicators effectively, and write comprehensive unit, widget, and integration tests to ensure the robustness of our application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*61GTOQAYuf_JH20y1SMdUg.jpeg" /></figure><p>Let’s start by introducing some of the keywords that we are going to pass through in this article:</p><p><strong>setUp<br></strong>If you want to register any function to run before the test, you can call that function here! So it will be called before each test is run.<br>If this is called within a test group, it applies only to tests in that group.</p><p><strong>build</strong><br>Used to construct and return the bloc under test.</p><p><strong>act</strong><br>act is an optional callback which will be invoked with the bloc under test and should be used to interact with the bloc. So if you want to send an event to the bloc, it goes here.</p><p><strong>expect</strong> <br>An optional Function that returns a Matcher which the bloc under test is expected to emit after act is executed.</p><h3>Unit Test</h3><p>Unit test, as the name suggests, used to test small units of code, in order to verify the behavior of a single function, method, or class.</p><p>Our goal will be writing unit tests for the DogsBloc, so let’s divide the unit testing section into segments, each one discuss a part of the code undergoing the unit testing procedures.</p><p>First, we are going to use the setUp function to construct the bloc before the test is run</p><pre>late DogsBloc bloc;<br>setUp(() {<br>  bloc = DogsBloc(petsRepository: MockDogsRepo());<br>});</pre><p>Instead of passing DogsRepo(), we created a mock of DogsRepo, and pass it to the DogsBloc.</p><p><strong>MockDogsRepo<br></strong>Mocked data play an important role in automated tests. A developer can use test mocks to avoid reaching out to a database in production, and help the tester to narrow test scopes and focus on specific parts of the codebase</p><p>This mocked class, will re-implement loadListOfPets function, as we are going to return the data from locally stored file, contains a list of dogs, as fetched from the production API end-point.<br>So dogsMockedJsonList is the json list of dogs .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cae10d31e8d1ce7b1e8113bdeb7f60e5/href">https://medium.com/media/cae10d31e8d1ce7b1e8113bdeb7f60e5/href</a></iframe><p>To simulate the pagination part in the end-point, we added the following snippet of code:</p><pre>.sublist(page! * limit!, page * limit + limit);</pre><p>While rangeErorr represents the error thrown incase trying to access elements that exceeded the length of dogs list data.</p><p><strong>Test Dogs Bloc initial state<br></strong>As defined in PetsBloc, the initial state of the bloc is an empty state PetsState.empty(). To test that, we can use test function with the help on expect function to match the bloc state with the expected initial state.</p><pre>test(<br>  &#39;Dogs tab initial state&#39;,<br>  () =&gt; expect(bloc.state, const PetsState.empty()),<br>);</pre><p><strong>Test fetching first patch of data<br></strong>Let’s define a blocTest, which accept DogsBloc &amp; PetsState, and add the test description</p><pre>blocTest&lt;DogsBloc, PetsState&gt;(<br>  &#39;first time fetch dogs data&#39;,<br>);</pre><p>Through the build function, will return the bloc, which is already constructed with the setUp function</p><pre>blocTest&lt;DogsBloc, PetsState&gt;(<br>  &#39;first time fetch dogs data&#39;,<br>  build: () =&gt; bloc,<br>);</pre><p>We want to send a new event to bloc to load list of dogs, which is LoadPetsListEvent(), that can achieved with the act function.</p><pre>act: (bloc) =&gt; bloc.add(const LoadPetsListEvent()),</pre><p>So far, we constructed the bloc, sent LoadPetsListEvent to the bloc, so we are expecting the state to be changed corresponding to the injected events as following: Loading State → Successfully Fetched Data State</p><pre>expect: () =&gt; [    <br>    // The first state after the event is triggered<br>    const PetsState(isLoading: true, error: null, data: null),<br>    <br>    // The next state, after the data is loaded successfully!<br>    PetsState(<br>      isLoading: false,<br>      error: null,<br>      data: dogsMockedJsonList.map((i) =&gt;<br>      Pet.fromJson(i)).toList().sublist(0, 10),<br>    ),<br>  ],</pre><p>The data in the second expected state, is the first 10 elements of the list of dogs, as this is the first fetch of data, supposed to contain the elements with indexes from 0 → 9</p><p>Gathering all these code parts together, we’ll get the following unit testing snippet</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/33417af9a71884be76f37e81ac7f9e49/href">https://medium.com/media/33417af9a71884be76f37e81ac7f9e49/href</a></iframe><p>Now, let’s test fetching the second patch of data!</p><p><strong>Test fetching second patch of data (Load More)<br></strong>We need to insert another LoadPetsListEvent at the act callback, so it looks like this:</p><pre>act: (bloc) {<br>  bloc.add(const LoadPetsListEvent());<br>  bloc.add(const LoadPetsListEvent());<br>},</pre><p>While the state should be changed corresponding to those events, as following:<br>Loading State → Successfully Fetched Data State (Data from 0 → 10)<br>→ Fetched Data (from 0 → 10) → Successfully Fetched Data (from 0 → 20)</p><p>And the expect callback will be:</p><pre>expect: () =&gt; [ <br>  /// first patch<br>  const PetsState(isLoading: true, error: null, data: null),<br>  PetsState(<br>    isLoading: false,<br>    error: null,<br>    data: dogsMockedJsonList.map((i) =&gt;<br>    Pet.fromJson(i)).toList().sublist(0, 10),<br>  ),<br><br>  <em>/// second patch<br>  </em>PetsState(<br>    isLoading: true,<br>    error: null,<br>    data: dogsMockedJsonList.map((i) =&gt;<br>    Pet.fromJson(i)).toList().sublist(0, 10),<br>  ),<br>  PetsState(<br>    isLoading: false,<br>    error: null,<br>    data: dogsMockedJsonList.map((i) =&gt;<br>    Pet.fromJson(i)).toList().sublist(0, 20),<br>  ),<em><br></em>],</pre><p><strong>Equality Operation &amp; States Comparison</strong></p><p>One thing we always need to keep an eye on while writing tests, is the <strong>equality operation ==<br></strong>We need to compare states and ensure that the emitted state is equal to the expected state. To do this correctly, we need to override the == operator, followed by the hash code function. You can use a library to override these operations in your classes, or you can write the methods yourself for the necessary classes, as we’re going to do here.</p><p>In PetsState class, we need t override the mentioned methods:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/11ef7cba0d6e4bfe0c9ee2e918b18690/href">https://medium.com/media/11ef7cba0d6e4bfe0c9ee2e918b18690/href</a></iframe><p>So to consider two PetsStates are equal, they need to get the same isLoading boolean variable, and the same error object, and finally the same list of dogs, in the same order. That’s why we use the isEqualInOrder extension, which implements a way to make sure two lists have the same elements in the same order.</p><h3>Firebase Auth Unit Test</h3><p>In order to unit test Flutter Firebase authentication, we need to mock the FirebaseAuth class. This can be done using the <a href="https://pub.dev/packages/firebase_auth_mocks">firebase_auth_mocks</a> package. The firebase_auth_mocks package provides a mock class that implements the FirebaseAuth API. This allows us to simulate the behavior of FirebaseAuth in our unit tests.</p><p><strong>Test initial state<br></strong>Let’s start by testing the initial state of bloc state. By testing the initial state, we can ensure that the bloc is in the correct state when it is first created. This helps to prevent bugs from occurring later in the code.</p><p>Let’s start by creating a mock FirebaseAuth instance and a mock User instance. The mock FirebaseAuth instance must be configured to be signed out. The setUp() function creates an instance of the AuthBloc and passes the mock FirebaseAuth instance to it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d363ffbcf1713bf96492ffb3f0739890/href">https://medium.com/media/d363ffbcf1713bf96492ffb3f0739890/href</a></iframe><p><strong>Test successful login<br></strong>After a successful login, we expect the state to change from LoggedOutState to LoggedInState</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e30023dbd6bfe1edd0268274e02643a3/href">https://medium.com/media/e30023dbd6bfe1edd0268274e02643a3/href</a></iframe><p>The previous snippet of code tests the login functionality of a bloc, as we can ensure that the bloc correctly transitions from the LoggedOutState state to the LoggedInState state when a user logs in successfully.</p><p><strong>Test login with exception<br></strong>FirebaseAuth can throw exceptions if the login or signup fails. We need to handle these exceptions in our unit tests. We can do this by using the <a href="https://pub.dev/packages/mock_exceptions">mock_exceptions</a> package.</p><p>The following code shows how to use the mock_exceptions package to mock an exception:</p><pre>final authWithLoginException = MockFirebaseAuth();<br><br>whenCalling(Invocation.method(#signInWithEmailAndPassword,null))<br>.on(authWithLoginException).thenThrow(<br>FirebaseAuthException(code: &#39;invalid-email&#39;));</pre><p>whenCalling() function is mocking the signInWithEmailAndPassword() method. <br>The signInWithEmailAndPassword() method takes two arguments: the email address and the password. <br>The whenCalling() function is passing the null value for both arguments.</p><p>The function that is called when the signInWithEmailAndPassword() method is called is the thenThrow() function. <br>The thenThrow() function takes an exception object as an argument. In this case, the thenThrow() function is throwing a FirebaseAuthException object with the code invalid-email.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c716878031cd76d678648b4187be983f/href">https://medium.com/media/c716878031cd76d678648b4187be983f/href</a></iframe><p>We will keep the Register unit test for the reader as an exercise, as it is very similar to the login unit test process.</p><h3>Widget Test</h3><p>Flutter widget test helps developers ensure that the user interface (UI) of their app behaves as expected. These tests simulate user interactions with widgets and verify that the corresponding UI changes are accurate.</p><p>To test the Dogs List Page, we will start by preparing the widget related to the page. To simplify this process, we should consider what is needed for this widget to work, such as repositories or BloC providers.</p><p>Since we are only testing the Dogs section, we do not need to initialize the rest of the repositories or providers. Therefore, the first patch of widget test will look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/30e6031ac3d7bd858eac28992cbcc82d/href">https://medium.com/media/30e6031ac3d7bd858eac28992cbcc82d/href</a></iframe><p>For this widget test, the process is simple. We just need to scroll down and verify that each time we get new data, which is retrieved from the mocked repository.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/171374069d93d08903e50170fd5b63a9/href">https://medium.com/media/171374069d93d08903e50170fd5b63a9/href</a></iframe><p>scrollUntilVisible Repeatedly scrolls a [Scrollable] by delta in the direction until a widget matching finder is visible.</p><p>Testing the Cats tab will be similar to the previous widget test for the Dogs tab, so we will skip that for now and move on to writing a widget test for the home page.</p><p>We will begin by preparing the widget with the necessary BloC providers and mocked repositories.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/45e92d43352b728e9fca8d54b4e10ed0/href">https://medium.com/media/45e92d43352b728e9fca8d54b4e10ed0/href</a></iframe><p>To test the functionality of the tabs, we can simply switch between the two tabs as follows</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d397036149be69ea24757eed0f456a1/href">https://medium.com/media/5d397036149be69ea24757eed0f456a1/href</a></iframe><p>We will leave it to you to check the data on each tab after it’s been switched to.</p><h3>Firebase Auth Widget Test</h3><p>in this section, we will walk through how to test the login screen. We will write widget tests that verify the behavior of the login screen widgets.</p><p>Once we have created a mock FirebaseAuth instance, we can create a widget test that verifies the behavior of the login screen widgets. The following code shows an example of a widget test that verifies the presence of the email and password text fields, and the login button:</p><pre>testWidgets(&#39;Test login page widgets&#39;, (WidgetTester tester) async {<br>  // sets up the mock FirebaseAuth instance and the Flutter app <br>  await prepareLoginScreen(tester);<br><br>  var emailTextFormField = find.byType(EmailTextFieldWidget);<br>  expect(emailTextFormField, findsOneWidget);<br><br>  var passwordTextFormField = find.byType(PasswordTextFieldWidget);<br>  expect(passwordTextFormField, findsOneWidget);<br><br>  var loginButton = find.widgetWithText(BlackButton, &#39;Login&#39;);<br>  expect(loginButton, findsOneWidget);<br>});</pre><p>and here’s the snippet of code where we prepare the widget test for login page:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5f71143c9ffd50ddf7f1a0cc96d1ee96/href">https://medium.com/media/5f71143c9ffd50ddf7f1a0cc96d1ee96/href</a></iframe><p>We are going to insert an email and password, while the MockFirebaseAuth will accept the credentials and emits a successful login attempt.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eb2bcc681f0b994a000ceda2eedd83fd/href">https://medium.com/media/eb2bcc681f0b994a000ceda2eedd83fd/href</a></iframe><h3>Integration Test</h3><p>Integration testing is a type of software testing that verifies how individual components of a software system interact with each other. In the context of Flutter, integration tests verify how Flutter widgets interact with each other and with the underlying platform.</p><h4>How can I run the integration test?</h4><p>Integration tests are designed to test the app’s behavior and functionality when all the individual components of the app are integrated and working together. To run these tests, you need a device or a simulator to simulate user interactions with the app and to verify that the app’s behavior and functionality meet the expected results.<br>Also, you need to remember that integration test folder should follow this directory structure:</p><pre>lib/<br>  ...<br>integration_test/<br>  foo_test.dart<br>  bar_test.dart<br>test/<br>  # Other unit tests go here.</pre><p>To prepare the integration test, you should add the following line at the first of the integration test main function:</p><pre>IntegrationTestWidgetsFlutterBinding.ensureInitialized()</pre><p>IntegrationTestWidgetsFlutterBinding is a class that provides a set of APIs for interacting with the Flutter framework during integration tests.<br>and this method to ensure that the IntegrationTestWidgetsFlutterBinding has been initialized. <br>Then, we can call the main function, from the main.dart file, as we start the app in a regular condition.</p><pre>    await app.main();</pre><p>In this section, we will try to cover a few scenarios, for different cases.</p><p>First scenario, the test will verify that the user is able to login to the app. The test will do this by:</p><ol><li>Make sure the user is logged out of the app.</li><li>Entering valid user’s email and password.</li><li>Tapping the Login button.</li><li>Verifying that the user is logged in and taken to the home page.</li></ol><p>To make sure the user is logged out of the app, you can add the following line of code:</p><pre>    await FirebaseAuth.instance.signOut();</pre><p>Here’s the full first scenario test:</p><p>In this article, we have explored advanced Bloc techniques and testing strategies to enhance the robustness and maintainability of your Flutter applications. We have delved into complex state management scenarios, and written comprehensive unit, widget, and integration tests. By applying these techniques, you can create more reliable and scalable Flutter applications that deliver exceptional user experiences</p><p>Visit the Github repository to check the full code.</p><p><a href="https://github.com/Ali-Assi-1994/cats_and_dogs_bloc">GitHub - Ali-Assi-1994/cats_and_dogs_bloc: Flutter Dogs &amp; Cats App Tutorial with BLoC State Management</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac6a33e5f8a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Flutter State Management with the BLoC Pattern]]></title>
            <link>https://medium.com/@ali_assi/mastering-flutter-state-management-with-the-bloc-pattern-2b3fc10ed3be?source=rss-f0b80b132721------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b3fc10ed3be</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[cubit]]></category>
            <category><![CDATA[bloc]]></category>
            <category><![CDATA[state-management]]></category>
            <dc:creator><![CDATA[Ali Assi]]></dc:creator>
            <pubDate>Thu, 05 Sep 2024 12:02:27 GMT</pubDate>
            <atom:updated>2024-09-05T12:05:17.419Z</atom:updated>
            <content:encoded><![CDATA[<p>Ever felt your Flutter app getting a little, well, messy in its own state? Working with your team on a big project and code spaghetti floating around?</p><p>Well, BLoC is here for the rescue, ready to save the day with its unidirectional data flow. This tutorial will guide you through building a pawsome pet adoption app that uses Bloc to fetch furry friends from the APIs, and implement endless scrolling so you can browse all the doggos and kitties your heart desires. Let’s Bloc our way to a better Flutter app!</p><h3><strong>What is BloC, and how does it work?</strong></h3><p><em>Are you ready for a few boring definitions before jumping to the code part?</em></p><p>Bloc is a simple, powerful, highly testable state management library, aims to separate presentation and business logic.</p><p>Basically, bloc relies on events to trigger state changes. In other words, Bloc receives incoming events and processes them to generate corresponding outgoing <em>states</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*V_TQw6xQSCdLj7elNoGVwg.png" /><figcaption>Bloc Architecture</figcaption></figure><ul><li><strong>Events</strong></li></ul><blockquote>Events are the input to a Bloc. They are commonly added in response to user interactions such as button presses or lifecycle events like page loads.</blockquote><ul><li><strong>States</strong></li></ul><blockquote>States are the output of a <strong>bloc </strong>and represent a part of your application’s state. UI components can be notified of states and redraw portions of themselves based on the current state.</blockquote><ul><li><strong>Bloc</strong></li></ul><blockquote>Bloc is a class where we register event handlers via the <strong><em>on&lt;Event&gt;</em></strong> API . An event handler is responsible for converting any incoming events into zero or more outgoing states.</blockquote><h3>Let’s kick it off!</h3><p>Let’s get serious now, are you a dog person or a cat person?<br>That might’ve caught you off guard, but don’t worry, we are gonna build an app for both dogs &amp; cats!</p><p>The app will contain two tabs, one for dogs, another for cats, and each one has a list of pets. To make it more straightforward, and more focused on Bloc pattern, we will start by preparing one of them, let it be ‘Pet’.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FRnzrErVKt7xRe%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FRnzrErVKt7xRe%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FRnzrErVKt7xRe%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="213" frameborder="0" scrolling="no"><a href="https://medium.com/media/fff93d742235759082afe3131eeb69a4/href">https://medium.com/media/fff93d742235759082afe3131eeb69a4/href</a></iframe><h4>1. Pets Events</h4><p>Looking into the Bloc class definition, you will find that it accepts only one type of events, and one type of states!!</p><pre>abstract class Bloc&lt;Event, State&gt; extends BlocBase&lt;State&gt;</pre><p>But wait, we are going to have multiple events! and we are expecting to produce multiple states! <br>No problem at all! We just need to define a superclass for events, and all the events will inherit the type of that class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ba97fe5620b56e17bfa321e194736c0/href">https://medium.com/media/4ba97fe5620b56e17bfa321e194736c0/href</a></iframe><p>It would be a good practice to define the superclass as an abstract, so you don’t instantiate the superclass and mistakenly trigger it as an event.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab3098ad30d703b78bff454a75394de5/href">https://medium.com/media/ab3098ad30d703b78bff454a75394de5/href</a></iframe><p>We have only one event for now, which is fetching the list from the API Service.</p><h4>2. Pets States</h4><p>To define the state of pets, as any data fetched from API, we will add the following variables</p><ul><li><strong>isLoading</strong>: To indicate the data is being loaded, and show a progress indicator</li><li><strong>error</strong>: incase an error has happened during data fetching</li><li><strong>data</strong>: list of pets fetched from the server</li></ul><p>and the pets state class should look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b5794f0f478f16d9619d91f1eb015c34/href">https://medium.com/media/b5794f0f478f16d9619d91f1eb015c34/href</a></iframe><p><em>It’s always good practice to define an empty state, which will be the initial state for the bloc when it’s first constructed</em></p><h4>3. Pets Bloc</h4><p>Now we can build the bloc. So we do have one event to handle, and the states will be changing according to the following:</p><ul><li><strong>Initial state</strong> will be PetsState.empty() and will be declared through calling the constructor of the super class super(PetsState.empty())</li><li>Event handler <strong><em>on&lt;Event&gt; </em></strong>should handle all the events in pets_events.dart</li><li>LoadPetsListEvent start by emitting a new state, where <br>isLoading = true, and keeping the same old data (list of pets),<br><em>you can access the old state by using the keyword </em><em>state.</em></li><li>Next, it’s time to fetch the data, wrap it with a try catch to handle errors.<br>When it’s <strong>fetched successfully</strong>, we set isLoading = false, and add the fetched data to the list of pets <em>(Again, we can access the old list of pets using </em><em>state)</em>.<br>Incase if any <strong>error is caught</strong>, we also set isLoading = false, keep the old list of data, and set the error in the new state<br>PetsState( isLoading: false, error: e, data: state.data)</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f7307b3161fbb58bb680a53bbc42232b/href">https://medium.com/media/f7307b3161fbb58bb680a53bbc42232b/href</a></iframe><p>After building the bloc section, let’s start with the UI…<br>But before heading to the UI part, as we are going to interact with the bloc part there, we need to understand how we can consume bloc:</p><h3>How To Consume Bloc?</h3><p>Now that you understand how Blocs work, let’s explore the tools you’ll use to integrate them into your UI:</p><ul><li><strong>BlocBuilder<br></strong>Handles building the widget in response to new states</li></ul><pre>BlocBuilder&lt;PetsBloc, PetsState&gt;(<br>  builder: (context, state) {<br>    // return widget here based on PetsState<br>  }<br>)</pre><ul><li><strong>BlocListener<br></strong>This widget never rebuild the UI, it would be perfect to listen to state changes, usually used for functionality that needs to occur once per state change, such as navigation, showing a snackbar or a dialog.</li></ul><pre>BlocListener&lt;PetsBloc, PetsState&gt;(<br>  listener: (context, state) {<br>    // Navigate, or show a dialog....<br>  }, <br>  child: Widget()<br>)</pre><ul><li><strong>BlocConsumer<br></strong>Need to build widgets &amp; a listen to state changes? BlocConsumer exposes a <strong>builder</strong> and <strong>listener</strong> in order to react to new states. Should only be used when it is necessary to both rebuild UI and execute other reactions to state changes in the <strong>bloc</strong>.</li></ul><pre>BlocConsumer&lt;PetsBloc, PetsState&gt;(<br>  listener: (context, state) {<br>    // Navigate, or show a dialog....<br>  },<br>  builder: (context, state) {<br>    // return widget here based on PetsState<br>  }<br>)</pre><ul><li><strong>BlocSelector<br></strong> Used to filter updates by selecting a new value based on the current bloc state. This widget help to prevent unnecessary builds, when selected value does not change.</li></ul><pre>BlocSelector&lt;PetsBloc, PetsState, 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><ul><li><strong>BlocProvider<br></strong>A widget which provides a bloc to its children</li></ul><pre>BlocProvider(<br>  create: (BuildContext context) =&gt; PetsBloc(),<br>  child: Widget(),<br>);</pre><p>By default, <strong>BlocProvider</strong> will create the bloc lazily, meaning <strong>create</strong> will get executed when the bloc is looked up via <strong>BlocProvider.of&lt;PetsBloc&gt;(context)<br></strong>To override this behavior and force <strong>create</strong> to be run immediately, <strong>lazy</strong> can be set to <strong>false</strong>.</p><ul><li><strong>MultiBlocProvider<br></strong>You can use it if you need to provide more than one bloc</li></ul><pre>MultiBlocProvider(<br>  providers: [<br>    BlocProvider&lt;PetsBloc&gt;(<br>      create: (BuildContext context) =&gt; PetsBloc(),<br>    ),<br>    BlocProvider&lt;AuthBloc&gt;(<br>      create: (BuildContext context) =&gt; AuthBloc(),<br>    ),<br>  ],<br>  child: Widget(),<br>)</pre><ul><li><strong>RepositoryProvider<br></strong>A widget which provides a repository to its children</li></ul><pre>RepositoryProvider(<br>  create: (context) =&gt; PetsRepository(),<br>  child: Widget(),<br>);</pre><ul><li><strong>MultiRepositoryProvider<br></strong>You can use it if you need to provide more than one repository</li></ul><pre>MultiRepositoryProvider(<br>  providers: [<br>    RepositoryProvider&lt;PetsRepository&gt;(<br>      create: (context) =&gt; PetsRepository(),<br>    ),<br>    RepositoryProvider&lt;AuthRepository&gt;(<br>      create: (context) =&gt; AuthRepository(),<br>    ),<br>  ],<br>  child: Widget(),<br>)</pre><h4>Pets List Screen</h4><p>It’s a screen contains a ListView, provided with a list of pets to view.</p><p>If the data is empty, and the bloc is not fetching any data, then we will start fetching process by adding loading pets event:</p><pre>if (!isLoading &amp;&amp; data!.isEmpty) {<br>  context.read&lt;PetsBloc&gt;().add(LoadPetsListEvent());<br>}</pre><p>If the bloc is fetching data, we will return a CircularProgressIndicator:</p><pre>if (isLoading) {<br>  return CircularProgressIndicator();<br>}</pre><p>Incase of error, let’s return a text with that error:</p><pre>if (error != null) {<br>  return Text(&#39;error ${state.error.toString()}&#39;);<br>}</pre><p>And here’s how the screen should look like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7dd9db43519fd7b2dce38c0d060baabc/href">https://medium.com/media/7dd9db43519fd7b2dce38c0d060baabc/href</a></iframe><h4>Dogs &amp; Cats List Screens</h4><p>So, we do have a page with list of dogs, and another one with a list of cats.<br>But these screens are similar as a UI, the only difference will be the Bloc provided in each screen.</p><p>Instead of building two separated screens, let’s try building one screen PetsListPage, that accept PetsBloc as a generic type, and this Bloc will be passed when creating instance of this screen, either for dogs or cats. It will look like this:</p><pre>class PetsListPage&lt;T extends PetsBloc&gt; extends StatelessWidget</pre><p>and each time you want to consume a bloc, you can write:</p><pre>context.read&lt;T&gt;()</pre><p>That’s how the pets list screen will be after that</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1349753eb6c500cb8642d4ba9abcba3e/href">https://medium.com/media/1349753eb6c500cb8642d4ba9abcba3e/href</a></iframe><p>To build instance of list screen, you can write:</p><pre>// to build dogs list screen<br>PetsListPage&lt;DogsBloc&gt;()</pre><pre>// to build cats list screen<br>PetsListPage&lt;CatsBloc&gt;()</pre><p>Where both of DogsBloc &amp; CatsBloc are extended classes for PetsBloc</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b4f628bef40d449d480aad641eacdb1/href">https://medium.com/media/2b4f628bef40d449d480aad641eacdb1/href</a></iframe><p>and that lead us to the repositories and data layer…</p><h3>Data Layer &amp; API Service</h3><p>First, we need a public API service, where (at least) we can fetch a list of dogs, and another list of cats. For that, we will be using <a href="https://thedogapi.com/">The Dog API</a> &amp; <a href="https://thecatapi.com/">The Cat API</a>.<br>You can sign up there, to get your free access which includes API secret key, to be sent in requests&#39; header.</p><p>To get a list of dogs, you can call the following get request<br>dogsBaseUrl/v1/images/search<br>While you can use the same for cats, just by changing the base url<br>catsBaseUrl/v1/images/search</p><p>As we can notice, that we have the same endpoint for both cats &amp; dogs, while the responses are almost similar, the major difference is the base url. <br>So, we can build one repository PetsRepository , and extend it to CatsRepository and DogsRepository where the base url can be overridden.</p><p>Data layer will consists of 3 main components:</p><ul><li>API Client (<a href="https://pub.dev/packages/dio">Dio</a> as we are using in this project)</li><li><a href="https://gist.github.com/Ali-Assi-1994/531b414cf78ddb0713465cb8e38d479b">PetsService</a> (Middleware class to connect the API Client with the repositories)</li><li><a href="https://gist.github.com/Ali-Assi-1994/de22e433eacb0b4ad0ec1a232ed95b97">PetsRepository</a> (Class that will handle getting data, <em>should be easily mocked for testing purposes</em>)</li></ul><p>PetsRepository will be extended to DogsRepository &amp; CatsRepository, which will override the base url, and API secret key</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ec8d57bff2c0cd69887bca224ce4337/href">https://medium.com/media/4ec8d57bff2c0cd69887bca224ce4337/href</a></iframe><p>Now, we don’t need to redefine API functions for cats or dogs, we write them only once, at the superclass PetsRepository, and the extended classes will be able to access them with the overridden url.</p><h4>List Pagination</h4><p>When the user reach the last available pet element, we need the to fetch the next patch of data.<br>Let’s start by listening to the scrollable list view, and notify the bloc that the user reached to the final pet and ready to see more!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6fa63aab9795e943afcc0fbdf59f118c/href">https://medium.com/media/6fa63aab9795e943afcc0fbdf59f118c/href</a></iframe><p>When the user has scrolled to the end of list view <em>(minus some margin ‘here it’s 100 pixel&#39;, since it’s better to start loading before hitting the last pixel in the list),</em></p><pre>metrics.pixels &gt;= metrics.maxScrollExtent - 100</pre><p>and we need to make sure that it’s not already fetching data, we don’t want to hit the loading action more than once per one end of scroll notification!<br>When these conditions are met, we trigger the bloc with LoadPetsListEvent</p><p>It would be nice to add loading indicator whenever bloc is fetching data, let it be a CircularProgressIndicator at the end of list. Let’s update the ListView as following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/607a3d66f0273696c3e92ef5d9f91efd/href">https://medium.com/media/607a3d66f0273696c3e92ef5d9f91efd/href</a></iframe><p>We increase the length of ListView items only when the bloc is loading, and concatenate the CircularProgressIndicator to the list of pets.</p><p>In PetsBloc, we need to define patch index, start with the value zero, and should be incremented after each successful data fetch.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f507ffeb591adc8d01ee32d007572fb4/href">https://medium.com/media/f507ffeb591adc8d01ee32d007572fb4/href</a></iframe><h4>Conclusion</h4><p>In this article, we’ve conquered the challenges of messy state management in Flutter by using the power of the Bloc pattern. We built a fun pet adoption app, showcasing how Bloc facilitates:</p><ul><li><strong>Fetching data from APIs:</strong> We seamlessly retrieved pet data, allowing users to browse their furry friends.</li><li><strong>Implementing endless scrolling (pagination):</strong> We ensured a smooth user experience by enabling endless scrolling through the pet listings.</li></ul><p>Check the full code on this repository:</p><p><a href="https://github.com/Ali-Assi-1994/cats_and_dogs_bloc">GitHub - Ali-Assi-1994/cats_and_dogs_bloc: Flutter Dogs &amp; Cats App Tutorial with BLoC State Management</a></p><p>By following this Bloc tutorial, you’ve gained valuable skills to tackle state management in your own Flutter projects. In future articles, we’ll delve deeper into advanced Bloc concepts and explore implementing unit and widget tests for your Bloc-based applications.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FRdx8SHjHhiVUI%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FRdx8SHjHhiVUI%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FRdx8SHjHhiVUI%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="554" frameborder="0" scrolling="no"><a href="https://medium.com/media/fdebac192bee055c0c2e0073841a68a0/href">https://medium.com/media/fdebac192bee055c0c2e0073841a68a0/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b3fc10ed3be" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>