How to make API calls using the Refresh Indicator and Provider package in Flutter.
Published: 2022-12-22 18:42:42

<p>Most of the apps you use have a feature that refreshes the page when you pull down from the top of the screen to refresh the page! It is called the Refresh indicator! Let's learn how to use them in flutter projects with the provider package! We will use a simple API from stoic-quotes</p>
<p>Link:- <a target="_blank" href="https://stoic-quotes.com/api/quote">https://stoic-quotes.com/api/quote</a></p>
<p>Step 1:- Open a new flutter project!</p>
<p>Step 2:- Integrate the <a target="_blank" href="https://pub.dev/packages/provider">provider</a> package from <code>pub.dev</code> in the <code>pubspec.yaml</code> file or simply use the command in your IDE terminal!</p>
<pre><code class="lang-dart">flutter pub add provider
</code></pre>
<p>Step 3:- Create a new file and name it anything you want. I'll name it the <code>providerfile.dart</code></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1671729872197/96664227-4c94-4555-8c35-4d10fec23c76.png" alt class="image--center mx-auto" /></p>
<p>Step 4:- Import the library in both files. Paste this command in both files. <code>main.dart</code> and <code>providerfile.dart</code> on top.</p>
<pre><code class="lang-dart"><span class="hljs-keyword">import</span> <span class="hljs-string">'package:provider/provider.dart'</span>;
</code></pre>
<p>Step 5:- Integrate the <a target="_blank" href="https://pub.dev/packages/http">HTTP</a> package from <code>pub.dev</code> in the <code>pubspec.yaml</code> or use the below command</p>
<pre><code class="lang-dart">flutter pub add http
</code></pre>
<p>Step 6:- Go to the <code>providerfile.dart</code> file and create a provider class that extends <code>ChangeNotifier</code>. Name the class <code>Refresher</code>. Add a String named <code>Quote</code>. Create a method named <code>updater</code> that can make the API call using the <code>HTTP</code> package! Don't forget to import the HTTP library in this file! Code below 👇</p>
<pre><code class="lang-dart"><span class="hljs-keyword">import</span> <span class="hljs-string">'package:flutter/cupertino.dart'</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">'package:provider/provider.dart'</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">'package:http/http.dart'</span> <span class="hljs-keyword">as</span> http;
<span class="hljs-keyword">import</span> <span class="hljs-string">'dart:convert'</span> <span class="hljs-keyword">as</span> convert;
<span class="hljs-keyword">import</span> <span class="hljs-string">'dart:convert'</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Refresher</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">ChangeNotifier</span> </span>{

  <span class="hljs-built_in">String</span> Quote = <span class="hljs-string">""</span>;
  <span class="hljs-built_in">String</span> Author = <span class="hljs-string">""</span>;

  <span class="hljs-keyword">void</span> updater() <span class="hljs-keyword">async</span> {
    <span class="hljs-keyword">var</span> url = <span class="hljs-built_in">Uri</span>.parse(<span class="hljs-string">"https://stoic-quotes.com/api/quote"</span>);
    <span class="hljs-keyword">var</span> response = <span class="hljs-keyword">await</span> http.<span class="hljs-keyword">get</span>(url);
    <span class="hljs-keyword">if</span> (response.statusCode == <span class="hljs-number">200</span>) {
      <span class="hljs-built_in">print</span>(<span class="hljs-string">"Works"</span>);
    }
    <span class="hljs-keyword">var</span> data = jsonDecode(response.body);
    <span class="hljs-built_in">print</span>(data);
    Quote = (data[<span class="hljs-string">"text"</span>]);
    Author = (data[<span class="hljs-string">"author"</span>]);

    notifyListeners();
  }
}
</code></pre>
<p>The <code>var data = jsonDecode(response.body);</code> decodes the response of the API call output!<br />and <code>Quote = (data["text"]);</code> takes the main quote text from the output. so does the <code>Author</code>. Don't forget the <code>notifyListeners();</code> in the end, or else the code won't work!</p>
<p>Step 7:- Now go to the <code>main.dart</code> file! and import the <code>providerfile.dart</code> file, also the official provider package. You need to activate the provider. In this <code>main.dart</code> file, create a stateless widget, with a scaffold, AppBar, and a body. The body consists of <code>RefreshIndicator</code> with <code>ListView</code> as its child. And <code>Column</code> with 2 <code>Text</code> Widgets as the child of <code>ListView</code>. Code below👇</p>
<pre><code class="lang-dart"><span class="hljs-keyword">import</span> <span class="hljs-string">'package:flutter/material.dart'</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">'package:provider/provider.dart'</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">'providerfile.dart'</span>;

<span class="hljs-keyword">void</span> main() {
  runApp(MultiProvider(
    providers: [
      ChangeNotifierProvider(create: (_) =&gt; Refresher()),
    ],
    child: MaterialApp(home: MyApp()),
  ));
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyApp</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">StatelessWidget</span> </span>{
  MyApp({Key? key}) : <span class="hljs-keyword">super</span>(key: key);

  <span class="hljs-meta">@override</span>
  Widget build(BuildContext context) {
    <span class="hljs-keyword">return</span> Scaffold(
      appBar: AppBar(
        title: <span class="hljs-keyword">const</span> Text(<span class="hljs-string">"Refresh Indicator"</span>),
      ),
      body: RefreshIndicator(
        edgeOffset: <span class="hljs-number">0.1</span>,
        backgroundColor: Colors.black,
        color: Colors.white,
        onRefresh: () <span class="hljs-keyword">async</span> {
          Provider.of&lt;Refresher&gt;(context, listen: <span class="hljs-keyword">false</span>).updater();
        },
        child: ListView(
          children: &lt;Widget&gt;[
            Column(
              children: &lt;Widget&gt;[
                Text(Provider.of&lt;Refresher&gt;(context, listen: <span class="hljs-keyword">false</span>).Quote),
                SizedBox(height: <span class="hljs-number">20</span>),
                Text(<span class="hljs-string">"-<span class="hljs-subst">${Provider.of&lt;Refresher&gt;(context, listen: <span class="hljs-keyword">false</span>).Author}</span>"</span>),
              ],
            ),
          ],
        ),
      ),
    );
  }
}
</code></pre>
<p>It's important to initialize the Provider in the <code>runapp</code> method, or else it won't work. Inside the refresh indicator's <code>onRefresh</code> function call the <code>updater</code> class from the <code>providerfile.dart</code> file. In the Text widget, you need to get the quote using the provider as mentioned in the code.</p>
<p>Done! Now run the app. It should work!</p>
<p>You can access this project on GitHub!<br />Link:- <a target="_blank" href="https://github.com/Rishikesh-278/ProviderAPIcalls">https://github.com/Rishikesh-278/ProviderAPIcalls</a></p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://vimeo.com/783721018">https://vimeo.com/783721018</a></div>
<p> </p>
<p>If you liked my article consider supporting me through <a target="_blank" href="https://www.buymeacoffee.com/RustyRishii">Buymeacoffee</a><br /><a target="_blank" href="https://linktr.ee/rustyrishii">https://linktr.ee/rustyrishii</a></p>
<p>Thanks for reading!</p>
</br><p style="color:#757CF9;">This article is published w/ <a target="_blank" href="https://scattr.io?ref=dev">Scattr  ↗️</a></p>