DEV Community

Cover image for How to make API calls using the Refresh Indicator and Provider package in Flutter.
Rishikesh Bidkar
Rishikesh Bidkar

Posted on • Originally published at rustyrishii.hashnode.dev

How to make API calls using the Refresh Indicator and Provider package in Flutter.

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

Link:- https://stoic-quotes.com/api/quote

Step 1:- Open a new flutter project!

Step 2:- Integrate the provider package from pub.dev in the pubspec.yaml file or simply use the command in your IDE terminal!

flutter pub add provider

Step 3:- Create a new file and name it anything you want. I'll name it the providerfile.dart

Step 4:- Import the library in both files. Paste this command in both files. main.dart and providerfile.dart on top.

import 'package:provider/provider.dart';

Step 5:- Integrate the HTTP package from pub.dev in the pubspec.yaml or use the below command

flutter pub add http

Step 6:- Go to the providerfile.dart file and create a provider class that extends ChangeNotifier. Name the class Refresher. Add a String named Quote. Create a method named updater that can make the API call using the HTTP package! Don't forget to import the HTTP library in this file! Code below ๐Ÿ‘‡

import 'package:flutter/cupertino.dart';
import 'package:provider/provider.dart';
import 'package:http/http.dart' as http;
import 'dart:convert' as convert;
import 'dart:convert';

class Refresher extends ChangeNotifier {

  String Quote = "";
  String Author = "";

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

    notifyListeners();
  }
}

The var data = jsonDecode(response.body); decodes the response of the API call output!
and Quote = (data["text"]); takes the main quote text from the output. so does the Author. Don't forget the notifyListeners(); in the end, or else the code won't work!

Step 7:- Now go to the main.dart file! and import the providerfile.dart file, also the official provider package. You need to activate the provider. In this main.dart file, create a stateless widget, with a scaffold, AppBar, and a body. The body consists of RefreshIndicator with ListView as its child. And Column with 2 Text Widgets as the child of ListView. Code below๐Ÿ‘‡

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'providerfile.dart';

void main() {
  runApp(MultiProvider(
    providers: [
      ChangeNotifierProvider(create: (_) => Refresher()),
    ],
    child: MaterialApp(home: MyApp()),
  ));
}

class MyApp extends StatelessWidget {
  MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Refresh Indicator"),
      ),
      body: RefreshIndicator(
        edgeOffset: 0.1,
        backgroundColor: Colors.black,
        color: Colors.white,
        onRefresh: () async {
          Provider.of<Refresher>(context, listen: false).updater();
        },
        child: ListView(
          children: <Widget>[
            Column(
              children: <Widget>[
                Text(Provider.of<Refresher>(context, listen: false).Quote),
                SizedBox(height: 20),
                Text("-${Provider.of<Refresher>(context, listen: false).Author}"),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

It's important to initialize the Provider in the runapp method, or else it won't work. Inside the refresh indicator's onRefresh function call the updater class from the providerfile.dart file. In the Text widget, you need to get the quote using the provider as mentioned in the code.

Done! Now run the app. It should work!

You can access this project on GitHub!
Link:- https://github.com/Rishikesh-278/ProviderAPIcalls

https://vimeo.com/783721018

If you liked my article consider supporting me through Buymeacoffee
https://linktr.ee/rustyrishii

Thanks for reading!

This article is published w/ Scattr โ†—๏ธ

Top comments (0)