<?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 Appala Reddy on Medium]]></title>
        <description><![CDATA[Stories by Appala Reddy on Medium]]></description>
        <link>https://medium.com/@appalareddi394?source=rss-c0d2ca29c93------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*jQtX-wVuEudn2GuP</url>
            <title>Stories by Appala Reddy on Medium</title>
            <link>https://medium.com/@appalareddi394?source=rss-c0d2ca29c93------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 04:10:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@appalareddi394/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 Reusable API Call Cubit]]></title>
            <link>https://medium.com/@appalareddi394/flutter-bloc-reusable-api-call-cubit-a247f59a074a?source=rss-c0d2ca29c93------2</link>
            <guid isPermaLink="false">https://medium.com/p/a247f59a074a</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-bloc]]></category>
            <dc:creator><![CDATA[Appala Reddy]]></dc:creator>
            <pubDate>Sat, 06 May 2023 08:05:04 GMT</pubDate>
            <atom:updated>2023-05-06T08:05:04.729Z</atom:updated>
            <content:encoded><![CDATA[<p>I have been working with the <a href="https://pub.dev/packages/flutter_bloc">flutter_bloc</a> package for a while now. Anybody who worked with this package might tell you that, you might have to write a bit of boilerplate code to get what you trying to achieve with this package like making an API call and feeding that result back to UI.</p><p>So I have decided to write a reusable cubit class which will reduce the effort of creating a new cubit for an API call. So following is what I was able to come up with.</p><p>Packages Used: <a href="https://pub.dev/packages/flutter_bloc">flutter_bloc</a>, <a href="https://pub.dev/packages/dartz">dartz</a>, <a href="https://pub.dev/packages/freezed">freezed</a>, <a href="https://pub.dev/packages/freezed_annotation">freezed_annotation</a></p><h3><strong>Solution</strong></h3><h4>Build: NetworkRequestCubit and Failure</h4><p>The solution primarily involves 2 files <strong>network_request_cubit.dart </strong>and <strong>network_request_cubit.freezed.dart </strong>(generated by freezed package). And this solution assumes that you will return <strong>Either </strong>type from your request</p><ol><li>Create a dart file and name it <strong>network_request_cubit.dart</strong> and paste the below code into that file.</li></ol><pre>import &#39;dart:async&#39;;<br><br>import &#39;package:dartz/dartz.dart&#39;;<br>import &#39;package:flutter_bloc/flutter_bloc.dart&#39;;<br>import &#39;package:freezed_annotation/freezed_annotation.dart&#39;;<br><br>import &#39;failure.dart&#39;;<br><br>part &#39;network_request_cubit.freezed.dart&#39;;<br><br>/// T -&gt; output type<br>/// RP -&gt; request params type<br>class NetworkRequestCubit&lt;T, RP&gt; extends Cubit&lt;NetworkRequestState&lt;T&gt;&gt; {<br>  NetworkRequestCubit({required this.onRequest}) : super(NetworkRequestState&lt;T&gt;.initial());<br><br>  final Future&lt;Either&lt;Failure, T&gt;&gt; Function(RP? params, NetworkRequestState&lt;T&gt; state) onRequest;<br><br>  Future&lt;void&gt; request([RP? params]) async {<br>    try {<br>      emit(NetworkRequestState&lt;T&gt;.loading());<br><br>      final result = await onRequest(params, state);<br>      result.fold((l) =&gt; emit(NetworkRequestState&lt;T&gt;.failure(l)), (r) =&gt; emit(NetworkRequestState&lt;T&gt;.success(r)));<br>    } catch (e, st) {<br>      print(e);<br>      print(st);<br>      emit(NetworkRequestState&lt;T&gt;.failure(Failure(error: &quot;Something went wrong&quot;)));<br>    }<br>  }<br>}<br><br>@freezed<br>class NetworkRequestState&lt;T&gt; with _$NetworkRequestState&lt;T&gt; {<br>  const NetworkRequestState._();<br><br>  const factory NetworkRequestState.initial() = _NetworkRequestInitial&lt;T&gt;;<br><br>  const factory NetworkRequestState.loading() = _NetworkRequestLoading&lt;T&gt;;<br><br>  const factory NetworkRequestState.success(T data) = _NetworkRequestSuccess&lt;T&gt;;<br><br>  const factory NetworkRequestState.failure(Failure failure) = _NetworkRequestFailure&lt;T&gt;;<br>}</pre><p>2. Create a dart file and name it <strong>failure.dart</strong> and paste the below code into that file. (this can be replaced with your custom error/failure class)</p><pre>import &#39;package:freezed_annotation/freezed_annotation.dart&#39;;<br><br>part &#39;failure.freezed.dart&#39;;<br><br>@freezed<br>class Failure with _$Failure {<br>  const factory Failure({<br>    required String error,<br>  }) = _Failure;<br>}</pre><p>3. Run the build runner package to generate the necessary files</p><pre>flutter pub run build_runner build --delete-conflicting-outputs</pre><p>By now, you will have a reusable cubit class that you can use it for your use cases. Let’s see how can we use this to make an API call using bloc architecture.</p><h4>Usecase:</h4><p>A cubit that will fetch holdings summary for an investment profile from an API call.</p><h4>Create: A new NetworkRequestCubit</h4><pre>typedef HoldingsSummaryCubit = NetworkRequestCubit&lt;HoldingsSummary, String&gt;;<br>typedef HoldingsSummaryCubitState = NetworkRequestState&lt;HoldingsSummary&gt;;<br><br>// A method which will create HoldingsSummaryCubit which fetches holdings summary<br>// from ReportsRepo repository<br>HoldingsSummaryCubit createSummaryCubit(ReportsRepo repo) {<br>  return HoldingsSummaryCubit(onRequest: (profileId, state) =&gt; repo.fetchHoldingSummary(profileId));<br>}</pre><h4><strong>Usage: BlocProvider, BlocBuilder</strong></h4><p>This is no different than how you use normal Cubit/Bloc. And to add an event, you have to call <strong>request(RP? params) </strong>method on the <strong>NetworkRequestCubit </strong>class.</p><pre>@override<br>Widget build(BuildContext context) {<br>  ReportsRepo repo = ...;<br>  String profileId = &quot;123&quot;;<br><br>  return BlocProvider(<br>    create: (ctx) =&gt; createSummaryCubit(repo)..request(profileId),<br>    child: HoldingsSummaryWidget(),<br>  );<br>}</pre><pre>@override<br>Widget build(BuildContext context) {<br><br>  return BlocBuilder&lt;HoldingsSummaryCubit, HoldingsSummaryCubitState&gt;(<br>      builder: (context, state) {<br>        // render your widget based on the state<br>      },<br>  );<br>}</pre><p>That’s it. I hope you learned something new. Please let me know your feedback.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a247f59a074a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>