Open In App

Flutter – Fetching JSON Data using HTTP

Last Updated : 09 Nov, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will learn how to fetch data from the internet or JSON file using the HTTP package in a flutter.

What is HTTP?

The HTTP is a composable, future-based library for making HTTP requests. This package contains a set of high-level functions and classes that make it easy to consume HTTP resources. It’s multi-platform and supports mobile, desktop, and browser.

Implementation:

We are assuming you already know how to make a project in a Flutter, we will be working on vs code.

The following steps are:

Step 1: Create a project in Vs code, And remove the default code.

Step 2: Before writing the code just add the HTTP plugin in your pubspec yaml file.

dependencies:
 http: ^0.13.3

OR you can simply add your plugin from the terminal just type this command,

flutter pub add http

After that run this command for getting the packages,

flutter pub get

Step 3: In main.dart file call the main() function , inside it run the runApp( ) method and give it an App (MyApp).

Step 4: Now create a stateful widget with the name ‘MyApp’. A stateful widget is a widget that changes their state during runtime, and return  the MaterialApp( ), MaterialApp has so many properties , but here we use only 2 or 3, make the debugBanner: false title : “MyApi”  and in the home property  give a widget as you want, we give it MyApi( ).

Dart




import 'package:flutter/material.dart';
import 'package:workingwithhttp2/MyApi.dart';
 
void main() {
  runApp(MyApp());
}
 
class MyApp extends StatefulWidget {
  MyApp({Key? key}) : super(key: key);
 
  @override
  _MyAppState createState() => _MyAppState();
}
 
class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: "MyApi",
      debugShowCheckedModeBanner: false,
      home: MyApi(),
    );
  }
}


Now let’s create the class MyApi, you can work on the same file but here we are working in different files for a different task, so we create a new file MyApi.dart.

Step 5: In MyApi.dart file, make a stateful widget MyApi and return the scaffold. In scaffold, there is an appBar and in the appBar we have a title :”Geeks for Geeks “, and in the body, we have a widget myApiWidget( ).

Dart




import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
 
class MyApi extends StatefulWidget {
  MyApi({Key? key}) : super(key: key);
 
  @override
  _MyApiState createState() => _MyApiState();
}
 
class _MyApiState extends State<MyApi> {
   @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Geeks for Geeks"),
      ),
      body: myApiWidget(),
    );
  }
}


For data, we have this JSON file.

Step 6: Now let’s fetch this data using HTTP, create a function fetchUsers ,  and call the get function by HTTP instances. It returns the list of objects.

Dart




Future<List<dynamic>> fetchUsers() async {
  var result =
      await http.get(Uri.parse("https://randomuser.me/api/?results=20"));
  return jsonDecode(result.body)['results'];
}


Step 7: We have to call the fetchUsers().  But it is good to load data at initializing our APP, for that, we have a init( ) method.  

Dart




@override
void initState() {
  response = fetchUsers();
  super.initState();
}


Ohh great, we fetch the data successfully, now It’s time to display it.

Step 8: Create a myApiWidget(). 

Dart




myApiWidget() {
  return FutureBuilder(
    future: response,
    builder: (BuildContext context, AsyncSnapshot snapshot) {
      if (snapshot.hasData) {
        return ListView.builder(
          itemCount: snapshot.data.length,
          itemBuilder: (BuildContext context, int index) {
            return Card(
              child: Column(
                children: [
                  ListTitle(
                    title: Text(snapshot.data[index]['name']['title'] +
                        " " +
                        snapshot.data[index]['name']['first'] +
                        " " +
                        snapshot.data[index]['name']['last']),
                    trailing:
                        Text(snapshot.data[index]['dob']['age'].toString()),
                    leading: CircleAvatar(
                      backgroundImage: NetworkImage(
                        snapshot.data[index]['picture']['large'],
                      ),
                    ),
                    subtitle: Text(snapshot.data[index]['email']),
                  )
                ],
              ),
            );
          },
        );
      } else {
        return Center(
          child: CircularProgressIndicator(),
        );
      }
    },
  );
}
myApiWidget() {
  return FutureBuilder(
    future: response,
    builder: (BuildContext context, AsyncSnapshot snapshot) {
      if (snapshot.hasData) {
        return ListView.builder(
          itemCount: snapshot.data.length,
          itemBuilder: (BuildContext context, int index) {
            return Card(
              child: Column(
                children: [
                  ListTile(
                    title: Text(snapshot.data[index]['name']['title'] +
                        " " +
                        snapshot.data[index]['name']['first'] +
                        " " +
                        snapshot.data[index]['name']['last']),
                    trailing:
                        Text(snapshot.data[index]['dob']['age'].toString()),
                    leading: CircleAvatar(
                      backgroundImage: NetworkImage(
                        snapshot.data[index]['picture']['large'],
                      ),
                    ),
                    subtitle: Text(snapshot.data[index]['email']),
                  )
                ],
              ),
            );
          },
        );
      } else {
        return Center(
          child: CircularProgressIndicator(),
        );
      }
    },
  );
}


Output:   



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads