Open In App

Flutter – Fetching List of Data From API Through Dio

Improve
Improve
Like Article
Like
Save
Share
Report

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?

  • Dio makes networking feel simple and manages several edge circumstances. 
  • Dio makes it simpler to manage several network requests running simultaneously while providing the security of a sophisticated error-handling method. 
  • Additionally, it enables you to avoid the boilerplate code required to track any file upload progress using the HTTP package.

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

Dart




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:

Output Screen

 

Step 3: Make a GET request using the Dio package

  • For this, we have created a function called getData()
  • Calling the function in the initState()

 

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

  • First, we used itemCount to fetch the length how many items are there in data that are coming from API
  • Now To see data on screen we are using the Title and Subtitle feature. 
  • Title will show the names of SuperHeros and Subtitle will show the powers of Superheros from the Data that the API is having.

 

Output Screen:

Output Screen

 

Step 5: Now show the image on the screen 

  • We have used Image.network under ListTile which fetch image data from the API
  • Using the ClipRRect property we are showing the image in Circular form.

 

Output Screen:

Output Screen

 

Complete Code

Dart




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:

 



Last Updated : 02 Feb, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads