Open In App

Flutter – Fetching List of Data From API Through Dio

Dio is a powerful HTTP client for Dart, which supports Interceptors, Global configuration, FormData, File downloading, etc. and Dio is very easy to use. In this article, we will learn how to use Dio in Flutter to make API Calls and show data in ListView. Before heading toward its implementation.

Why Use Dio For Internet calls?

Now Let’s dive into the code to learn how Dio works to make API Calls and show data in ListView.



Step By Step Implementation

Step 1: Add the Dio package in pubspec.yaml file and import it

 

 



Step 2: Build basic UI using ListView Builder




import 'dart:convert';
  
import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
  
void main() {
  runApp(const MyApp());
}
  
class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
  
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.green,
      ),
      home: const MyHomePage(),
    );
  }
}
  
class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);
  
  @override
  State<MyHomePage> createState() => _MyHomePageState();
}
  
class _MyHomePageState extends State<MyHomePage> {
  @override
  void initState() {
    getData();
  }
  
  void getData() async {
    try {
      var response = await Dio()
      print(response);
    } catch (e) {
      print(e);
    }
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          'GeeksForGeeks',
          style: TextStyle(color: Colors.white),
        ),
        centerTitle: true,
      ),
      body: ListView.builder(
          itemCount: 10,
          itemBuilder: (BuildContext context, int index) {
            return Card(
                child: ListTile(
              title: Text('name'),
              subtitle: Text('power'),
            ));
          }),
    );
  }
}

Output Screen:

 

Step 3: Make a GET request using the Dio package

 

Step 4: To show data on the screen that is coming from an API

 

Output Screen:

 

Step 5: Now show the image on the screen 

 

Output Screen:

 

Complete Code




import 'dart:convert';
  
import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
  
void main() {
  runApp(const MyApp());
}
  
class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
  
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.green,
      ),
      home: const MyHomePage(),
    );
  }
}
  
class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);
  
  @override
  State<MyHomePage> createState() => _MyHomePageState();
}
  
class _MyHomePageState extends State<MyHomePage> {
  var jsonList;
  @override
  void initState() {
    getData();
  }
  
  void getData() async {
    try {
      var response = await Dio()
      if (response.statusCode == 200) {
        setState(() {
          jsonList = response.data['superheros'] as List;
        });
      } else {
        print(response.statusCode);
      }
    } catch (e) {
      print(e);
    }
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          'GeeksForGeeks',
          style: TextStyle(color: Colors.white),
        ),
        centerTitle: true,
      ),
      body: ListView.builder(
          itemCount: jsonList == null ? 0 : jsonList.length,
          itemBuilder: (BuildContext context, int index) {
            return Card(
                child: ListTile(
              leading: ClipRRect(
                borderRadius: BorderRadius.circular(80),
                child: Image.network(
                  jsonList[index]['url'],
                  fit: BoxFit.fill,
                  width: 50,
                  height: 50,
                ),
              ),
              title: Text(jsonList[index]['name']),
              subtitle: Text(jsonList[index]['power']),
            ));
          }),
    );
  }
}

Final Output:

 


Article Tags :