Calling API In Flutter Using HTTP Request

In this tutorial we will learn how to use HTTP Package in flutter. HTTP request is used to fetch the data from the internet, It can be JSON format or in any other format.

http in flutter
http in flutter

What Is HTTP Request In Flutter?

HTTP is a package in flutter which is used to fetch the data from the cloud storage through an API. The API(Application Programming Interface) uses a URL from the server where the data is stored.

Most of the applications have the data stored in an online server. Also you can understand that almost all businesses have their app and websites, So their data remains the same on both app and website. For using the same data APIs are made for that. HTTP request is one of them.

Creating API In Flutter Using HTTP Dart Package

We can create POST, GET, PUT, DELETE and more requests to do operations with the server data. In the following example we will create some of the useful requests.

http
http

HTTP Dart Package In Flutter

First of all import the below package in your project file. The whole process uses the following steps :

  • Import the http dart package.
  • Make a network request using the http package.
  • Convert the response into a custom dart object.
  • Store the object into Model class.
  • Retrieve and show the data from the model.

Types of API Response JSON Data

There are many types of JSON data which we can get in API. We will fetch simple data and array which is sent by an API in the below example. The type of JSON data is shown in the screenshot.

1. Fetching Simple Format Of JSON Data Using HTTP package In Flutter – GET Request

In the below example we will fetch all the data using get request without passing any body parameters. After fetching the data will be shown.

Simple Json Format
Simple Json Format

Requirement To Fetch Simple JSON Data

To fetch simple type JSON data in flutter using HTTP package, we needed to create some classes which are as below:

  • ModelClass.dart
  • MainClass.dart

Add http package in pubspec.yaml

First of all add these dependencies in your pubspec.yaml file and click on pub get. You can add the latest package from here.

pubspec.yaml
pubspec.yaml

Then import the following packages in your classes where you are creating HTTP request.

import 'dart:convert';
import 'package:http/http.dart' as http;

Internet Permission

Additionally in your Manifest.xml file add the below internet permission for android. And for IOS no need to do anything.

<uses-permission android:name="android.permission.INTERNET"/>

ModelClass.dart

The ModelClass will be as below you can create the variables according to your API response.

class ModelClass {
  final int id;
  String email;
  String name;
  String phone;

  ModelClass({
    this.id,
    this.email,
    this.name,
    this.phone,
  });

  factory ModelClass.fromJson(dynamic json) {
    return ModelClass(
      id: json['id'] as int,
      name: json['email'],
      email: json['name'],
      phone: json["phone"],
    );
  }
}

Please note that the names -> json[‘id’] , json[’email’] , json[‘name’], json[“phone”], Should be same as the name of parameters of the API.

MainClass.dart

In this class we will make the HTTP request using the Future method and will pass the Model class in the Future method. And async and await is used to run the process in background.

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

class SupportFragment extends StatefulWidget {
  @override
  _SupportFragmentState createState() => _SupportFragmentState();
}

class _SupportFragmentState extends State<SupportFragment> {
  final Color myColor = Color(0xFF15A2EB);
  final Color myColorLightGray = Color(0xFF989E9E);

  final Color text_semi_black_color = Color(0xFF414B51);
  final Color text_gray_color = Color(0xFF70787C);

  ModelClass _model;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getSupport();
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        title: Text("Demo"),
      ),
      body: _model != null
          ? SingleChildScrollView(
              child: Container(
                child: Column(
                  children: [
                    Text(_model.email, style: TextStyle(fontSize: 18),),
                    Text(_model.name, style: TextStyle(fontSize: 18),),
                    Text(_model.phone, style: TextStyle(fontSize: 18),),
                  ],
                ),
              ),
            )
          : Center(child: CircularProgressIndicator()),
    );
  }

//method to make http request
  Future<ModelClass> getSupport() async {
    var response = await http.get(
      "https://localhost:3000/getUserList",
    );

    if (response.statusCode == 200) {
      var res = json.decode(response.body);
      //insert data into ModelClass
      _model = ModelClass.fromJson(res);
    } else {
      // show error
      print("Try Again");
    }
  }
}

Explanation

In the above MainClass the below method is used to make HTTP request. Pass the ModelClass as parameter in Future. To make a get request we have to use http.get(url) and pass the URL inside it.

 Future<ModelClass> getSupport() async {
    var response = await http.get(
      "https://localhost:3000/getUserList",
    );

    if (response.statusCode == 200) {
      var res = json.decode(response.body);
      //insert data into ModelClass
      _model = ModelClass.fromJson(res);
    } else {
      // show error
      print("Try Again");
    }
  }

2. Fetching Array Using HTTP Package In Flutter – POST Request

In the above example we learnt how to make a http request with get request with simple JSON format data. Now in the below example we will fetch array type JSON data shown as in below image using POST request.

Json Array
Json Array

I have a list of users where id of users are different but uid is same for some users. Now I want to fetch those users which uid is equals to 102 ( as saved in database ).

Requirements For HTTP Request In Flutter

  • ModelClass1.dart
  • ModelClass2.dart
  • MainClass.dart

Model Classes

Here we require two model classes for holding the data. ModelClass1 will hold the data which is outer of the array like success and totalResult and the object of the ModelClass2. ModelClass2 will hold the id, name, email, phone and uid.

ModelClass1.dart

Create the variables which are in outer part of the array in JSON. Create another class ModelClass2 and create its variable here.

import 'package:flutter/material.dart';
import 'package:mera_interest_flutter/model/AccountsListDataModel.dart';

class ModelClass1 {
  int success;
  int totalResults;
  List<ModelClass2> result;

  ModelClass1(this.success, this.totalResults, [this.result]);

  factory ModelClass1.fromJson(dynamic json) {
    if (json['result'] != null) {
      var tagObjsJson = json['result'] as List;
      List<ModelClass2> _tags =
          tagObjsJson.map((tagJson) => ModelClass2.fromJson(tagJson)).toList();

      return ModelClass1(
          json['success'] as int, json['totalResults'] as int, _tags);
    }
  }

  @override
  String toString() {
    return '{${this.success}, ${this.totalResults}, ${this.result}}';
  }
}

ModelClass2.dart

Create all the variables which are inside the array in the JSON response. And the name should be same as in the api parameters name.

class ModelClass2 {
  final int id;
  String email;
  String name;
  String phone;
  int uid;

  ModelClass2({
    this.id,
    this.email,
    this.name,
    this.phone,
    this.uid
  });

  factory ModelClass2.fromJson(Map<String, dynamic> json) {
    return ModelClass2(
      id: json['id'] as int,
      name: json['email'],
      email: json['name'],
      phone: json["phone"],
      uid: json["uid"] as int,
    );
  }
}

MainClass.dart

We will create HTTP request to fetch the array JSON by passing a uid with POST request in flutter class. Use below function inside in your MainClass.dart.

List<ModelClass2> _list;

Future<ModelClass1> getAccountList() async {

    ModelClass1 _accountListModel;
    String uid= "102";

    var bodyData = new Map<String, dynamic>();
    bodyData['uid'] = uid;
    

    var response = await http.post(
      "http://localhost:3000/getUserListArray",
      body: bodyData,
    );

    if (response.statusCode == 200) {
      var res = json.decode(response.body);
      _accountListModel = ModelClass1.fromJson(res);
      if (_accountListModel.success == 1) {
        var data = res["result"] as List;

        setState(() {
          _list = data
              .map<ModelClass2>((json) => ModelClass2.fromJson(json))
              .toList();
        });
      }
    } else {}
    return _accountListModel;
  }

How To Pass Body Parameters in POST Request – HTTP Flutter

To pass body parameters create a map object and add the parameters as below as we used in above example. And pass the object into Post request. You can pass multiple parameters by providing the name.

  String uid = "102";

    var bodyData = new Map<String, dynamic>();
    bodyData['uid'] = uid;
    
    var response = await http.post(
      "http://localhost:3000/getUserListArray",
      body: bodyData,
    );

How To Pass Headers In HTTP Post Request in Flutter

Most of the APIs require Headers you can pass it as below.

  String user_id = "116";
    var bodyData = new Map<String, dynamic>();
    bodyData['user_id'] = user_id;

     //headers
    final Map<String, String> headers = {
      "Content-type": "application/x-www-form-urlencoded",
      "api_key": "1234sopesn987$%*&*^",
      "secret_key": "@@^%&^kdsfkjdkf",
    };

    var response = await http.post(
      url,
      headers: headers,
      body: bodyData,
    );

How To get The Data From ModelClass.

To get the data from ModelClasses, First you have to create these variables in the class not in the function.

Getting Data From ModelClass1.dart

ModelClass1 model1 = new ModelClass1();
model1.success and model.totalResult

Getting Data From ModelClass2.dart

To show the data of ModelClass2 you have to create its object of List<ModelClass2> type. Mostly this data can be display using the ListView().

List<ModelClass2> _list;
_list[0].name,
_list[0].email,
_list[0].phone,
_list[0].uid

You can pass the _list into the ListView.Builder() to create a listView of the fetched list to show the data in list form. You can learn how to create a listView in flutter and pass the list from here in easy way.

Thank you for visiting this tutorial. Hope this will help you lot. You can comment for any issue and problem in the comment section below.

Donโ€™t miss new tips!

We donโ€™t spam! Read our [link]privacy policy[/link] for more info.

Leave a Comment

Translate ยป
Scroll to Top