<?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 Syed Ahmed Hamza Imam on Medium]]></title>
        <description><![CDATA[Stories by Syed Ahmed Hamza Imam on Medium]]></description>
        <link>https://medium.com/@hamzaimam?source=rss-125dc0ec1e08------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*JQcFWJhDgfvwOgw_cmw8Nw.jpeg</url>
            <title>Stories by Syed Ahmed Hamza Imam on Medium</title>
            <link>https://medium.com/@hamzaimam?source=rss-125dc0ec1e08------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 11:13:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hamzaimam/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[Reduce the boilerplate code of Bloc state management in Flutter using generic states (2/2)]]></title>
            <link>https://medium.com/@hamzaimam/reduce-the-boilerplate-code-of-bloc-state-management-in-flutter-using-generic-states-2-2-d5d4cefc534b?source=rss-125dc0ec1e08------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5d4cefc534b</guid>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[bloc]]></category>
            <category><![CDATA[pagination]]></category>
            <dc:creator><![CDATA[Syed Ahmed Hamza Imam]]></dc:creator>
            <pubDate>Fri, 23 Feb 2024 07:47:45 GMT</pubDate>
            <atom:updated>2024-02-23T07:47:45.131Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XSfE-mMPuU0IFzGsh2LGww.png" /></figure><p>Before diving into this article I suggest you read the previous article (<a href="https://medium.com/@hamzaimamcsa/reduce-the-boilerplate-code-of-bloc-state-management-in-flutter-using-generic-states-1-2-99d038870c8b"><strong>Link</strong></a>) for better understanding.</p><p>Now we are moving toward the second article to learn how to paginate data on screen with the same approach of generic states. Here I have made some changes to the previous code by adding <strong>DataBaseServices </strong>class which help to separate API call from Bloc/Cubit.</p><p>This is the class where you put all your API calls or follow them according to your project structure. You do not need to understand this code snippet here I have just mimicked the API call nothing else.</p><pre>class DataBaseServices {<br>  final bool showEmptyState, showErrorState;<br>  DataBaseServices({<br>     this.showEmptyState = false,<br>     this.showErrorState = false,<br>  });<br>  Future&lt;List&lt;Article&gt;&gt; getArticles(int page) async {<br>    return Future.delayed(const Duration(milliseconds: 2000), () {<br>      List&lt;Article&gt; articles = [];<br>      if (showEmptyState) {<br>        return articles;<br>      }<br>      if (showErrorState) {<br>        throw &#39;&#39;;<br>      }<br>      if (page &lt; 5) {<br>        int id = (page - 1) * 10;<br>        for (int i = 1; i &lt;= 10; i++) {<br>          final articleID = id + i;<br>          articles.add(Article(<br>            id: id,<br>            title: &#39;Article Title $articleID&#39;,<br>            content: &#39;Article Content $articleID&#39;,<br>          ));<br>        }<br>      }<br>      return articles;<br>    });<br>  }<br><br>Future&lt;Article?&gt; getArticle(int articleID)async{<br>    return await Future.delayed(<br>        const Duration(<br>          milliseconds: 2000,<br>        ), () async {<br>          final id = articleID-1;<br>      //Just to create different state Data not found and error states<br>      if (id == 2) {<br>        return null;<br>      } else {<br>        //Using array of article<br>        return articles[id];<br>      }<br>    });  <br>  }<br>}</pre><p>Now we add one more state which is <strong>UpdatePageState </strong>with <strong>hasMoreData </strong>bool check to show loader/shimmer until data is loading or pagination end on screen.</p><pre>class UpdatePageState extends BlocState {<br>  bool hasMoreData = false;<br>  UpdatePageState({required this.hasMoreData})<br>      : super();<br>}</pre><h3>Generic cubit for pagination:</h3><p>Let’s discuss our generic cubit for pagination having some fields.</p><ol><li><strong>_data: </strong>Used to contain a list of data that we get from <strong>API.</strong></li><li><strong>_loading &amp; _hasMore: </strong>Used to control the calling of <strong>API</strong> calls and which to show loader/shimmer on-screen.</li><li><strong>_limit &amp; _page: </strong>Limit and page are used to paginate data page pass as a query parameter for API and limit is used to check if more pages left.</li><li><strong>dataFetchFunction: </strong>This function is used to call on-screen which passes from the cubit that is created by extending <strong>GetPaginatedDataCubit&lt;T&gt;</strong> class.</li><li><strong>errorMessage and dataNotFoundMessage: </strong>This is used to show messages on the screen in case of any error or no data available.</li></ol><p>I have added comments for a better understanding of the code.</p><pre>class GetPaginatedDataCubit&lt;T&gt; extends Cubit&lt;BlocState&gt; {<br>  final List&lt;T&gt; _data = [];<br>  int _page = 1;<br>  bool _loading = false, _hasMore = true;<br>  late Future&lt;List&lt;T&gt;&gt; Function(int page) dataFetchFunction;<br>  final int _limit = 10;<br>  final String errorMessage, dataNotFoundMessage;<br><br>  GetPaginatedDataCubit.initialize({<br>    required BlocState initialState,<br>    required this.dataFetchFunction,<br>    required this.errorMessage,<br>    required this.dataNotFoundMessage,<br>  }) : super(initialState);<br><br>  ///Use to get length of list<br>  int getDataLength() =&gt; _data.length;<br><br>  ///Use to get item by index from list<br>  T getListItem(int index) =&gt; _data[index];<br><br>  _emitState(BlocState state) {<br>    if (!isClosed) {<br>      emit(state);<br>    }<br>  }<br><br>  ///Refresh bool is to refresh all data can be used with refreshindicator widget<br>  getData({bool refreshPagination = false}) async {<br>    try {<br>// reseting cubit data in case of referesh indicator is pulled<br>      if (refreshPagination) {<br>        _data.clear();<br>        _page = 1;<br>        _hasMore = true;<br>      }<br>      _emitState(UpdatePageState(hasMoreData: _hasMore));<br>// Stoping api call to hit again during async call<br>      if (!_loading) {<br>        _loading = true;<br>        final response = await this.dataFetchFunction(_page);<br>// handing to stop pagination<br>        if (response.isEmpty || response.length &lt; _limit) {<br>          _hasMore = false;<br>        } else {<br>// increamenting the page in case of more data available<br>          _page++;<br>        }<br>        _data.addAll(response);<br>        _loading = false;<br>// emiting state to update UI with new data and has more to show loading until pagination is stopped<br>        _emitState(UpdatePageState(hasMoreData: _hasMore));<br>      }<br><br>      if (this._data.isEmpty &amp;&amp; !_hasMore) {<br>        _emitState(DataNotFoundState(message: dataNotFoundMessage));<br>      }<br>    } catch (e) {<br>//emiting error state in case of any failure in api call<br>      _emitState(ErrorState(message: errorMessage));<br>    }<br>  }<br>}</pre><p>In the above code, we have named the constructor that we used to initialize the cubit and there is a method named <strong>getData()</strong> I have mentioned its functionality in the comments whose basic purpose is to handle pagination, populate the data list, and emit states. The other two methods <strong>getDataLength() </strong>and <strong>getListItem() </strong>used to help in pagination and making <strong>_data</strong> list a private variable.<strong>_emitState() </strong>function is to check cubit is not closed before emitting the state.</p><h3>Article Listing Screen (Paginate a list of data on-screen):</h3><p>Now let’s see how to use the <strong>GetPaginatedDataCubit </strong>on-screen we need to follow some steps.</p><ol><li>Declare the instance <strong>GetPaginatedDataCubit&lt;T&gt; </strong>with a specific ADT or datatype for our case it <strong>Article</strong>.</li><li>Initialize the <strong>GetPaginatedDataCubit&lt;Article&gt;</strong> instance in<strong> initState()</strong> and pass all the parameters such as <strong>API,</strong> error message, and no data message.</li><li>Call the <strong>getData() </strong>from <strong>GetPaginatedDataCubit&lt;Article&gt; </strong>to make the first API call and start loading on the screen.</li><li>Add listener to scroll controller to hit <strong>getData()</strong> at the end of scroll position.</li><li>Wrap your widget or screen with <strong>BlocProvider</strong> and <strong>BlocConsumer</strong> where you want to show the pagination.</li></ol><p>I have mentioned all these steps in the comments which help you to understand.</p><pre>class ArticleListingScreen extends StatefulWidget {<br>  final bool showEmptyState, showErrorState;<br>  const ArticleListingScreen(<br>      {super.key, this.showEmptyState = false, this.showErrorState = false});<br><br>  @override<br>  State&lt;ArticleListingScreen&gt; createState() =&gt; _ArticleListingScreenState();<br>}<br><br>class _ArticleListingScreenState extends State&lt;ArticleListingScreen&gt; {<br>  late GetPaginatedDataCubit&lt;Article&gt; _articlesListCubit;<br>  late DataBaseServices _db;<br>  late ScrollController _controller;<br><br>  @override<br>  void initState() {<br>    super.initState();<br>    _db = DataBaseServices(<br>      showEmptyState: widget.showEmptyState,<br>      showErrorState: widget.showErrorState,<br>    );<br><br>//Initialzing the pagination cubit and passing api call function error message and empty state message<br>    _articlesListCubit = GetPaginatedDataCubit.initialize(<br>        initialState: InitialState(null),<br>        dataFetchFunction: _db.getArticles,<br>        errorMessage: &#39;Something went wrong.&#39;,<br>        dataNotFoundMessage: &#39;Articles not found.&#39;);<br><br>//API call to get initial data of page 1 which starts loading on screen<br>    _articlesListCubit.getData();<br><br>//Initializing the controller and condition to hit API call at the end of page<br>    _controller = ScrollController();<br>    _controller.addListener(() {<br>      if (_controller.position.maxScrollExtent == _controller.position.pixels) {<br>        _articlesListCubit.getData();<br>      }<br>    });<br>  }<br><br>  @override<br>  void dispose() {<br>    // TODO: implement dispose<br>    _articlesListCubit.close();<br>    super.dispose();<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        title: const Text(&#39;Article Listing Screen&#39;),<br>      ),<br>      //Wrapping with bloc provider<br>      body: BlocProvider&lt;GetPaginatedDataCubit&lt;Article&gt;&gt;(<br>        create: (context) {<br>          return _articlesListCubit;<br>        },<br>        child: RefreshIndicator(<br>          onRefresh: () async {<br>            //passing refresh check true to reset the pagination cubit<br>            _articlesListCubit.getData(refreshPagination: true);<br>          },<br>          // consumer to update UI accoring to states emit from cubit<br>          child: BlocConsumer&lt;GetPaginatedDataCubit&lt;Article&gt;, BlocState&gt;(<br>              listener: (context, state) {},<br>              builder: (context, state) {<br>                if (state is UpdatePageState) {<br>                  return ListView.separated(<br>                      controller: _controller,<br>                      padding: const EdgeInsets.all(10),<br>                      itemCount: _articlesListCubit.getDataLength() +<br>                          (state.hasMoreData ? 1 : 0),<br>                      separatorBuilder: (context, index) {<br>                        return const SizedBox(<br>                          height: 10,<br>                        );<br>                      },<br>                      itemBuilder: (context, index) {<br>                        if (index &lt; _articlesListCubit.getDataLength()) {<br>                          final article = _articlesListCubit.getListItem(index);<br>                          return ListTile(<br>                            leading:Text(&#39;Article ID: ${article.id}&#39;),<br>                            title: Text(article.title),<br>                            subtitle: Text(article.content),<br>                            tileColor: Colors.deepPurple[100],<br>                            onTap: () {<br>                              Navigator.push(context,<br>                                  MaterialPageRoute(builder: (context) {<br>                                return ArticleScreen(articleId: article.id,);<br>                              }));<br>                            },<br>                          );<br>                        } else {<br>                          return const Center(<br>                            child: Padding(<br>                              padding: EdgeInsets.all(8.0),<br>                              child: CircularProgressIndicator(),<br>                            ),<br>                          );<br>                        }<br>                      });<br>                } else if (state is DataNotFoundState) {<br>                  return Center(<br>                    child: Text(state.message),<br>                  );<br>                } else if (state is ErrorState) {<br>                  return Center(<br>                    child: Text(state.message),<br>                  );<br>                } else {<br>                  return const Center(<br>                    child: CircularProgressIndicator(),<br>                  );<br>                }<br>              }),<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><p>Now it&#39;s time to see how our app works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*rhKPPIPV4wUT04pCnQftKw.gif" /><figcaption>Article pagination and fetching each article using bloc with generic states</figcaption></figure><p><strong>Conclusion: </strong>Generic states help to render UI on different screens without creating multiple specific states and provide a general solution for all types of responses from API you just need to parse the data into <strong>ADT </strong>and<strong> </strong>apply your business logic. The rest of the work of handling data and state management will be done by <strong>GetDataCubit </strong>and<strong> GetPaginatedDataCubit.</strong></p><p>I mostly use this approach with GET API, not with POST or other methods but still, it reduces so much effort and redundant work for getting and showing data on screen.</p><p>Code repo: <a href="https://github.com/smhamzaimam/bloc_statemanagement.git"><strong>GitHub</strong></a></p><p>I hope you find this article insightful, Please share your thoughts or any suggestions on my <a href="https://www.linkedin.com/in/syed-ahmed-hamza-imam-868101111/"><strong>LinkedIn</strong></a><strong>.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5d4cefc534b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reduce the boilerplate code of Bloc state management in Flutter using generic states (1/2)]]></title>
            <link>https://medium.com/@hamzaimam/reduce-the-boilerplate-code-of-bloc-state-management-in-flutter-using-generic-states-1-2-99d038870c8b?source=rss-125dc0ec1e08------2</link>
            <guid isPermaLink="false">https://medium.com/p/99d038870c8b</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[bloc-state-management]]></category>
            <category><![CDATA[pagination]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Syed Ahmed Hamza Imam]]></dc:creator>
            <pubDate>Fri, 23 Feb 2024 07:44:53 GMT</pubDate>
            <atom:updated>2024-02-23T07:44:53.230Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XSfE-mMPuU0IFzGsh2LGww.png" /></figure><p>Hi Folks! I am writing this article to share my practices for reducing boilerplate code in bloc state management using generic states so that you don&#39;t need to create redundant states every time for different screens. Before reading this article you must have a basic understanding of how bloc state management works. Hope you find this article helpful.</p><p>First of all, this is a series of articles.</p><ol><li>In the first one, we learn how to fetch simple data on-screen using generic states and generic cubit.</li></ol><p>2. In the second one, we learn about how to paginate a list of data on-screen with the same generic state and cubit approach.</p><p>I am using Cubit for this approach because it is easy to understand and if you already work with “Provider” you will find this article helpful to understand basic Bloc state management. In Bloc, we just emit the states instead of calling <strong>notifyListener()</strong> method as we did in the P<strong>rovider</strong>.</p><p>So let&#39;s start our journey.</p><h3><strong>Generic States:</strong></h3><p>Let&#39;s talk about all possible states in any GET method API call.</p><pre>abstract class BlocState {<br>  BlocState();<br>}<br><br>class InitialState extends BlocState {<br>  dynamic data;<br>  InitialState(this.data) : super();<br>}<br><br>class LoadingState extends BlocState {<br>  LoadingState() : super();<br>}<br><br>class DataFoundState&lt;T&gt; extends BlocState {<br>  T data;<br>  DataFoundState({required this.data})<br>      : super();<br>}<br><br>class DataNotFoundState extends BlocState {<br>  String message;<br>  DataNotFoundState({required this.message})<br>      : super();<br>}<br><br>class ErrorState extends BlocState {<br>  String message;<br>  ErrorState({required this.message})<br>      : super();<br>}</pre><ol><li><strong>InitialState</strong>: This state we use to initialize the cubit and we can also pass required data in this state that we can use in query parameters or in the body of API call. This data can be objectID, sortType, filters, etc.</li><li><strong>LoadingState: </strong>This state is to show the loader (Circular loader or shimmer)on-screen until the API call gets completed.</li></ol><p>On completion of the API call, we have these three possible states,</p><p>3. <strong>DataFoundState&lt;T&gt;: </strong>This state is used to show data that we fetch from the API on screen. I made this class generic to pass the data to the screen because data from the response can be parsed in any data type.</p><p>4. <strong>DataNotFoundState: </strong>This state is used if the API call is completed with no data in response. You can also send a message from the API to display on the screen.</p><p>5. <strong>ErrorState: </strong>This state is used when any API call fails and no data is available to show on the screen. You can also send a message in this state as we did in <strong>DataNotFoundState.</strong></p><h3>Generic Cubits:</h3><pre>class GetDataCubit extends Cubit&lt;BlocState&gt; {<br>  GetDataCubit(InitialState initializeState) : super(initializeState);<br><br>  _emitState(BlocState state) {<br>    if (!isClosed) {<br>      emit(state);<br>    }<br>  }<br><br>  emitDataState&lt;T&gt;(<br>      {required Future&lt;T&gt; Function() fetchData,<br>      required String errorMessage,<br>      required String dataNotFoundMessage}) async {<br>    try {<br>      _emitState(LoadingState());<br>      final data = await fetchData();<br>      if (data != null) {<br>        if (!super.isClosed) {<br>          _emitState(DataFoundState&lt;T&gt;(data: data));<br>        }<br>      } else {<br>        if (!super.isClosed) {<br>          _emitState(DataNotFoundState(<br>            message: dataNotFoundMessage,<br>          ));<br>        }<br>      }<br>    } catch (e) {<br>      if (!super.isClosed) {<br>        _emitState(ErrorState(<br>          message: errorMessage,<br>        ));<br>      }<br>    }<br>  }<br>}</pre><p>let&#39;s discuss about generic cubit having a single generic method emitDataState&lt;T&gt; with some parameters,</p><ol><li><strong>fetchData:</strong> This is an async function in which provider a nullable datatype is fetched from the API function.</li><li><strong>errorMessage</strong>: This is used to send an error message to the UI in case of failure.</li><li><strong>dataNotFoundMessage: </strong>This is used to show messages on UI if no data is found from API.</li></ol><p><strong>emitDataState&lt;T&gt;()</strong> is used to emit states first whole function wrap with try-catch block which triggers in case of API call fails so it emits <strong>ErrorState </strong>with<strong> errorMessage</strong>. If the future call is completed and data is not null then it emits <strong>DataFoundState&lt;T&gt; </strong>else it emits<strong> DataNotFoundState </strong>with <strong>dataNotFoundMessage</strong>. <strong>_emitState() </strong>function is to check cubit is not closed before emitting the state.</p><h3><strong>Using Generic Cubit as Article Cubit:</strong></h3><p>This is an article class you can use any datatypes or ADT to customize your cubit according to your needs.</p><pre>class Article {<br>  final String id;<br>  final String title;<br>  final String content;<br><br>  Article({<br>    required this.id,<br>    required this.title,<br>    required this.content,<br>  });<br><br>  factory Article.fromJson(Map&lt;String, dynamic&gt; json) {<br>    return Article(<br>        id: json[&#39;id&#39;], title: json[&#39;title&#39;], content: json[&#39;content&#39;]);<br>  }<br>}<br><br>List&lt;Article?&gt; articles = [<br>  Article(id: &#39;ID: 1&#39;, title: &#39;Article Title 1&#39;, content: &#39;Article Content 1&#39;),<br>  Article(id: &#39;ID: 2&#39;, title: &#39;Article Title 2&#39;, content: &#39;Article Content 2&#39;),<br> <br>];</pre><p>Here I extend the G<strong>etDataCubit </strong>so where <strong>_getArticle() </strong>will be your API call which is private because you do not need to call it directly. Then another method <strong>getArticle() </strong>which calls the cubit <strong>emitDataState&lt;T&gt;() </strong>where I pass the <strong>_getArticle(), errorMessage</strong>, <strong>dataNotFoundMessage</strong> as parameters, and <strong>emitDataState&lt;T&gt;() </strong>is now responsible for emitting all relevant states and handling API calls as we discuss above.</p><pre>class ArticleCubit extends GetDataCubit {<br>  InitialState initState;<br>  ArticleCubit({required this.initState}) : super(initState);<br><br>  Future&lt;Article?&gt; _getArticle() async {<br>    //Here i mimic api call<br>    return await Future.delayed(<br>        const Duration(<br>          milliseconds: 2000,<br>        ), () async {<br>      //Just to create different state Data not found and error states<br>      if ((initState.data as int) == 3) {<br>        return null;<br>      } else {<br>        //Using array of article<br>        return articles[initState.data as int];<br>      }<br>    });<br>  }<br><br>  getArticle() {<br>    super.emitDataState&lt;Article?&gt;(<br>      fetchData: _getArticle,<br>      errorMessage: &#39;Something went wrong!&#39;,<br>      dataNotFoundMessage: &#39;Article not found&#39;,<br>    );<br>  }<br>}</pre><p>If-Else condition in the function is just to emit <strong>DataNotFoundState </strong>and <strong>ErrorState.</strong></p><p>Now it is time to use our <strong>ArticleCubit </strong>and see how it works.</p><h3><strong>Article screen (F</strong>etching data on-screen<strong>):</strong></h3><p>On-screen you need to do these simple steps,</p><ol><li>Initialize the CustomCubit (ArticleCubit) with article ID.</li><li>Call <strong>getArticle() </strong>method.</li><li>Wrap your screen or specific widget with <strong>BlocProvider </strong>and<strong> BlocConsumer </strong>whose states need to be maintained.</li><li>Finally use states that emit from cubit to render different widgets.</li></ol><p><strong>BlocProvider: </strong>This works as an inherited widget and provides the instance of bloc/cubit to all its descendent widgets in the tree.</p><p><strong>BlocConsumer: </strong>This is a builder that listens to any state changes and rebuilds the widget on which it is wrapped.</p><pre><br>class ArticleScreen extends StatefulWidget {<br>  final int articleId;<br>  const ArticleScreen({super.key, required this.articleId});<br><br>  @override<br>  State&lt;ArticleScreen&gt; createState() =&gt; _ArticleScreenState();<br>}<br><br>class _ArticleScreenState extends State&lt;ArticleScreen&gt; {<br>//Instance of cubit <br>late ArticleCubit articleCubit;<br><br>  @override<br>  void initState() {<br>    super.initState();<br>//STEP 1: Initializing the cubit with article id<br>    articleCubit = ArticleCubit(initState: InitialState(widget.articleId));<br>//STEP 2: Calling get article having Article API (Delayed method return article)<br>  articleCubit.getArticle();<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        title: Text(&#39;Article ${widget.articleId+1}&#39;),<br>      ),<br>// STEP 3: Wraping with BlocProvider and BlocConsumer<br>      body: BlocProvider(<br>          create: (context) =&gt; articleCubit,<br>          child: BlocConsumer&lt;ArticleCubit, BlocState&gt;(<br>            builder: (context, state) {<br>              return Center(<br>                  child: Column(<br>                    mainAxisAlignment: MainAxisAlignment.center,<br>                children: [<br>//STEP 4: Here we are randering the UI based on states.<br>                  if (state is LoadingState)<br>                  const  Center(child:  CircularProgressIndicator(color: Colors.deepPurple,)),<br>                  if (state is DataFoundState&lt;Article?&gt;) ...[<br>                     Text(state.data!.id),<br>                     Text(state.data!.title),<br>                     Text(state.data!.content),<br>                  ],<br>                  if (state is DataNotFoundState) Text(state.message),<br>                  if (state is ErrorState) Text(state.message),<br>                ],<br>              ));<br>            },<br>            listener: (context, state) {},<br>          )),<br>    );<br>  }<br>}</pre><p>Now let’s see the final result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*EmyrQvZsUgdB-X9a41JQbA.gif" /></figure><p>You can find the GitHub repo in the second and last article of this series where you can also find code for pagination. Here is the link</p><h4><a href="https://medium.com/@hamzaimamcsa/reduce-the-boilerplate-code-of-bloc-state-management-in-flutter-using-generic-states-2-2-d5d4cefc534b">Reduce the boilerplate code of Bloc state management in Flutter using generic states (2/2)</a></h4><p>I hope you find this article insightful, Please share your thoughts or any suggestions on my <a href="https://www.linkedin.com/in/syed-ahmed-hamza-imam-868101111/"><strong>LinkedIn</strong></a><strong>.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99d038870c8b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>