<?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 Ahmet Özrahat on Medium]]></title>
        <description><![CDATA[Stories by Ahmet Özrahat on Medium]]></description>
        <link>https://medium.com/@ahmetozrahat?source=rss-1da55d36507c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*5ISOw9rti26vC7qs</url>
            <title>Stories by Ahmet Özrahat on Medium</title>
            <link>https://medium.com/@ahmetozrahat?source=rss-1da55d36507c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 13:04:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ahmetozrahat/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: Consuming API’s with Dio and BLoC]]></title>
            <link>https://medium.com/@ahmetozrahat/flutter-consuming-apis-with-dio-and-bloc-fe39b615a61c?source=rss-1da55d36507c------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe39b615a61c</guid>
            <category><![CDATA[bloc]]></category>
            <category><![CDATA[dios]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Ahmet Özrahat]]></dc:creator>
            <pubDate>Mon, 01 Jan 2024 18:40:41 GMT</pubDate>
            <atom:updated>2024-01-01T18:40:41.191Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*V_TQw6xQSCdLj7elNoGVwg.png" /></figure><h4>What is Dio and BLoC?</h4><p>As we start to create our brand new Flutter project and add some pages, we notice that it is time to implement the API calls and the state management.</p><p>While there might be another good approaches on consuming API’s in Flutter but today we will be taking a look how should it be done with Dio and BLoC packages. Dio is a HTTP networking package that makes API calls easy and customizable. By customizing I mean; You can add interceptors to the call like, add an API key to the Authorization header, catch the errors and repeat the request etc. On the other hand BLoC, which you may heard it before, is a state management package recommended by Google.</p><p>We will also use a minimal API provided by the RapidApi. It will be mentioned further in the article.</p><h4>Prepare Project</h4><p>Let’s create our Flutter project and add the dependencies to the pubspec.yaml file:</p><pre>dependencies:<br>  dio: ^5.4.0<br>  bloc: ^8.1.2<br>  flutter_bloc: ^8.1.3</pre><p>I will clean the boiler plate code generated by the Flutter engine to focus on the code we write. The project root folder now should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/304/1*wKslnF0qLkBA88PkXz9qhw.png" /><figcaption>Project folder structure.</figcaption></figure><p><strong><em>main.dart</em></strong> and <strong><em>home_page.dart</em></strong> file contents are respectively:</p><pre>import &#39;package:flutter/material.dart&#39;;<br><br>import &#39;home_page.dart&#39;;<br><br>void main() {<br>  runApp(const MyApp());<br>}<br><br>class MyApp extends StatelessWidget {<br>  const MyApp({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return MaterialApp(<br>      title: &#39;Flutter Demo&#39;,<br>      theme: ThemeData(<br>        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),<br>        useMaterial3: true,<br>      ),<br>      home: const HomePage(),<br>    );<br>  }<br>}</pre><pre>import &#39;package:flutter/material.dart&#39;;<br><br>class HomePage extends StatefulWidget {<br>  const HomePage({super.key});<br><br>  @override<br>  State&lt;HomePage&gt; createState() =&gt; _HomePageState();<br>}<br><br>class _HomePageState extends State&lt;HomePage&gt; {<br>  @override<br>  Widget build(BuildContext context) {<br>    return const Scaffold(<br>      body: Center(<br>        child: Text(&quot;Hello, world!&quot;),<br>      ),<br>    );<br>  }<br>}</pre><h4><strong>Creating Dio Client</strong></h4><p>Create a folder called <strong><em>data </em></strong>and inside the folder create file named: <strong><em>dio_client.dart</em></strong></p><pre>import &#39;package:dio/dio.dart&#39;;<br><br>import &#39;interceptors/auth_interceptor.dart&#39;;<br><br>class DioClient {<br>  static const String _baseUrl = &quot;https://moviesminidatabase.p.rapidapi.com/&quot;;<br><br>  DioClient() {<br>    addInterceptor(LogInterceptor());<br>  }<br><br>  final Dio dio = Dio(<br>    BaseOptions(baseUrl: _baseUrl),<br>  );<br><br>  void addInterceptor(Interceptor interceptor) {<br>    dio.interceptors.add(AuthInterceptor(dio: dio));<br>    dio.interceptors.add(interceptor);<br>  }<br>}</pre><p>Now create a folder called <strong><em>interceptors </em></strong>and add the file <strong><em>auth_interceptor.dart</em></strong> inside.</p><pre>import &#39;package:dio/dio.dart&#39;;<br><br>class AuthInterceptor extends Interceptor {<br>  final Dio dio;<br><br>  AuthInterceptor({<br>    required this.dio,<br>  });<br><br>  @override<br>  void onRequest(<br>      RequestOptions options, RequestInterceptorHandler handler) async {<br>    // Add your API key &amp; other stuff to the headers.<br>    options.headers.addAll({<br>      &quot;X-RapidAPI-Key&quot;: &quot;YOUR_API_KEY&quot;<br>    });<br>    options.headers<br>        .addAll({&quot;X-RapidAPI-Host&quot;: &quot;moviesminidatabase.p.rapidapi.com&quot;});<br>    handler.next(options);<br>  }<br><br>  @override<br>  void onError(DioException err, ErrorInterceptorHandler handler) async {<br>    if (err.response?.statusCode == 401) {<br>      // Refresh the token if the request results with status code of 401.<br>      return handler<br>          .resolve(await dio.fetch(err.requestOptions)); // Repeat the request.<br>    }<br><br>    return handler.reject(DioException(<br>      requestOptions: err.requestOptions,<br>      error: err.response,<br>    ));<br>  }<br>}</pre><blockquote>As you may noticed we have added X-RapidAPI-Key and X-RapidAPI-Host headers to the request. We will be using a minimal Movies API which returns a list of movie titles with any given year. You can reach the API by clicking here: <a href="https://rapidapi.com/SAdrian/api/moviesminidatabase/">https://rapidapi.com/SAdrian/api/moviesminidatabase/</a></blockquote><h4>Creating BLoC files</h4><p>If you are using Visual Studio Code with the BLoC extension you should be able to right click a folder and click to the option “Bloc: New Bloc”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*p6J5C76kiA3otFEmkAIWSA.png" /><figcaption>Creating BLoC folder and classes with the VSCode extension.</figcaption></figure><p>Enter the name of the BLoC and press Enter. Now the files should be created and looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/255/1*YzadO8J4OuE3sSxEaQMnTQ.png" /><figcaption>Created BLoC files.</figcaption></figure><p>Now, if you are familiar with the BLoC package we are going the define our events triggered by the UI and define our states emitted by the events. Then we will write the business logic to the <strong><em>movies_bloc.dart</em></strong> file.</p><p><strong><em>movies_state.dart</em></strong> file:</p><pre>part of &#39;movies_bloc.dart&#39;;<br><br>@immutable<br>sealed class MoviesState {}<br><br>final class MoviesInitial extends MoviesState {}<br><br>final class MoviesLoading extends MoviesState {}<br><br>final class MoviesSuccess extends MoviesState {<br>  final List&lt;Movie&gt; movies;<br><br>  MoviesSuccess({<br>    required this.movies,<br>  });<br>}<br><br>final class MoviesFailure extends MoviesState {<br>  final String errorMessage;<br><br>  MoviesFailure({<br>    required this.errorMessage,<br>  });<br>}</pre><p><strong><em>movies_event.dart</em></strong> file:</p><pre>part of &#39;movies_bloc.dart&#39;;<br><br>@immutable<br>sealed class MoviesEvent {}<br><br>final class MoviesFetchEvent extends MoviesEvent {}</pre><p><strong><em>movies_bloc.dart</em></strong> file:</p><pre>import &#39;dart:async&#39;;<br><br>import &#39;package:bloc/bloc.dart&#39;;<br>import &#39;package:medium_dio_bloc/data/dio_client.dart&#39;;<br>import &#39;package:medium_dio_bloc/model/movie.dart&#39;;<br>import &#39;package:meta/meta.dart&#39;;<br><br>part &#39;movies_event.dart&#39;;<br>part &#39;movies_state.dart&#39;;<br><br>class MoviesBloc extends Bloc&lt;MoviesEvent, MoviesState&gt; {<br>  MoviesBloc() : super(MoviesInitial()) {<br>    on&lt;MoviesFetchEvent&gt;(onMoviesFetchEvent);<br>  }<br><br>  FutureOr&lt;void&gt; onMoviesFetchEvent(<br>      MoviesFetchEvent event, Emitter&lt;MoviesState&gt; emit) async {<br>    emit(MoviesLoading());<br>    try {<br>      var client = DioClient();<br>      await client.dio.get(&quot;movie/byYear/2012/&quot;).then((value) {<br>        List&lt;Movie&gt; movies = (value.data[&quot;results&quot;] as List&lt;dynamic&gt;)<br>            .map((x) =&gt; Movie.fromMap(x))<br>            .toList();<br>        emit(MoviesSuccess(movies: movies));<br>      }).catchError((error) {<br>        emit(MoviesFailure(errorMessage: error.toString()));<br>      });<br>    } catch (e) {<br>      emit(MoviesFailure(errorMessage: e.toString()));<br>    }<br>  }<br>}</pre><blockquote>We only wrote the api endpoint because we have defined the base url in the DioClient class.</blockquote><p>Now create our model file called <strong><em>movie.dart</em></strong>:</p><pre>class Movie {<br>  final String imdb_id;<br>  final String title;<br><br>  Movie({<br>    required this.imdb_id,<br>    required this.title,<br>  });<br><br>  factory Movie.fromMap(Map&lt;String, dynamic&gt; map) {<br>    return Movie(<br>      imdb_id: map[&#39;imdb_id&#39;] as String,<br>      title: map[&#39;title&#39;] as String,<br>    );<br>  }<br>}</pre><p>And finally modify the home_page.dart file to have a simple UI which calls the API, fetches data and shows a response according to the status of API call:</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:flutter_bloc/flutter_bloc.dart&#39;;<br><br>import &#39;bloc/movies_bloc.dart&#39;;<br>import &#39;model/movie.dart&#39;;<br><br>class HomePage extends StatelessWidget {<br>  const HomePage({super.key});<br><br>  Widget _buildMovies(List&lt;Movie&gt; movies) =&gt; ListView.builder(<br>        itemCount: movies.length,<br>        itemBuilder: (context, index) =&gt; ListTile(<br>          title: Text(movies[index].title),<br>          subtitle: Text(movies[index].imdb_id),<br>        ),<br>      );<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      body: Center(<br>        child: BlocBuilder(<br>          bloc: MoviesBloc()..add(MoviesFetchEvent()),<br>          builder: (context, state) {<br>            switch (state.runtimeType) {<br>              case MoviesInitial:<br>              case MoviesLoading:<br>                return const Center(<br>                  child: CircularProgressIndicator(),<br>                );<br>              case MoviesSuccess:<br>                var movies = (state as MoviesSuccess).movies;<br>                return _buildMovies(movies);<br>              case MoviesFailure:<br>                var errorMessage = (state as MoviesFailure).errorMessage;<br>                return Center(<br>                  child: Text(errorMessage),<br>                );<br>              default:<br>                return Container();<br>            }<br>          },<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><p>Notice how we used StatelessWidget? This approach is also resource friendly if implemented properly.</p><p>If you hit the F5 button and launch the emulator/simulator you will see a similar screen to this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JYjv8SE_u8tT3820DTK8qw.png" /><figcaption>Screenshot of the app home page.</figcaption></figure><h4>Conclusion</h4><p>In this article we learned how to setup Dio and BLoC to consume API’s. Used RapidApi to test our application. Created a simple UI to demonstrate the work we have done. Please make a comment if you have any questions.</p><p>See you in the next article!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe39b615a61c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>