Skip to content
Related Articles

Related Articles

Improve Article

Implementing Rest API in Flutter

  • Difficulty Level : Hard
  • Last Updated : 31 Oct, 2020

Along with building a UI in Flutter, we can also integrate it with the backend. Most applications use API to display the uses data. We will use HTTP package, which provides advanced methods to perform operations. REST API uses simple http calls to communicate with JSON data because:

  • It uses await & async features.
  • It provides various methods.
  • It provides class and http to perform web requests.

Let us see how a JSON file is used to Fetch, Delete & Update data in a flutter app. We will make separate dart files of Main.dart for easier debugging & cleaner code in the following steps.

Step 1: Setting up the Project

Install the http dependency and add it in pubspec.yaml file in order to use API in the application.

dependencies:
  http:

Step 2: Creating a Request 

This basic request uses the get method to fetch the data from the specified URL in JSON format. Each request returns a Future<Response>. A Future<> is used to represent a potential value or error that will be available at some time in the future, for example, you made a request to a server now the response will take less than a few seconds, this time is represented from Future<>. Here, we use async & await feature which ensures that the response is asynchronous which means until & unless we get the response, it will not move further.

Future<List<Fruit>> fetchFruit() async {
final response = await http.get(url);
}
String url = "Your_URL";

Step 3: Creating the Classes

Create a Fruit class & saving as fruit.dart as shown below:



Dart




class Fruit {
  final int id;
  final String title;
  final String imgUrl;
  final int quantity;
  
  Fruit(
    this.id,
    this.title,
    this.imgUrl,
    this.quantity,
  );
  factory Fruit.fromMap(Map<String, dynamic> json) {
    return Fruit(json['id'], json['title'], json['imgUrl'], json['quantity']);
  }
  factory Fruit.fromJson(Map<String, dynamic> json) {
    return Fruit(json['id'], json['title'], json['imgUrl'], json['quantity']);
  }
}

Step 4: Create Class objects

Create the FruitItem in fruitItem.dart

Dart




import 'package:flutter/material.dart';
import 'fruit.dart';
  
class FruitItem extends StatelessWidget {
  FruitItem({this.item});
  
  final Fruit item;
  
  Widget build(BuildContext context) {
    return Container(
        padding: EdgeInsets.all(2),
        height: 140,
        child: Card(
          elevation: 5,
          child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: <Widget>[
                Image.network(
                  this.item.imgUrl,
                  width: 200,
                ),
                Expanded(
                    child: Container(
                        padding: EdgeInsets.all(5),
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                          children: <Widget>[
                            Text(this.item.title,
                                style: TextStyle(fontWeight: FontWeight.bold)),
                            Text("id:${this.item.id}"),
                            Text("quantity:${this.item.quantity}"),
                          ],
                        )))
              ]),
        ));
  }
}

Step 5: Create a List of fruits

Create a FruitList class in fruitList.dart as shown below:

Dart




import 'package:flutter/material.dart';
import 'fruit.dart';
import 'fruitItem.dart';
  
class FruitList extends StatelessWidget {
  final List<Fruit> items;
  
  FruitList({Key key, this.items});
  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemCount: items.length,
      itemBuilder: (context, index) {
        return FruitItem(item: items[index]);
      },
    );
  }
}

Step 6: Displaying the Responses

Display the response on the screen from main.dart file as shown below:

Dart




import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:flutter/material.dart';
import 'fruit.dart';
import 'fruitItem.dart';
import 'fruitList.dart';
  
class MyHomePage extends StatelessWidget {
  final String title;
  final Future<List<Fruit>> products;
  
  MyHomePage({Key key, this.title, this.products}) : super(key: key);
  
  @override
  Widget build(BuildContext context) 
  {
    return Scaffold(
        appBar: AppBar(
          backgroundColor: Color(0xFF4CAF50),
          title: Text("GeeksForGeeks"),
        ),
        body: Center(
          child: FutureBuilder<List<Fruit>>(
            future: products,
            builder: (context, snapshot) {
              if (snapshot.hasError) print(snapshot.error);
              return snapshot.hasData
                  ? FruitList(items: snapshot.data)
                  : Center(child: CircularProgressIndicator());
            },
          ),
        ));
  }
}

Following is the JSON Data upon running the application:

JSON Data



Following is the UI screen of the homepage of Flutter application with decoded JSON data.

Output:

fruit app

Explanation: 

1. This statement is used to import the package as http.

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

2. This statement is used to convert the JSON data.

import 'dart:convert';

3. The following statement is used in order to handle the error code. If the response status code is 200 then we can display the requested data otherwise we can show the error message to the user. Here, you can use any URL which is taking get() request and returning response in JSON format.

final response = await http.get('url');
 if (response.statusCode == 200) {
    //display UI} 
    else {
   //Show Error Message
   }
}

4. Following statements are used in order to decode the JSON data and display the output in a user-friendly manner. This ensures that it only accepts and extracts JSON data as per our requirement.

List<Fruit> decodeFruit(String responseBody) {
 final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();
 return parsed.map<Fruit>((json) => Fruit.fromMap(json)).toList();
}

Now Rest API is successfully implemented in the flutter app. If you need to update, delete, or send data in the Flutter app by using the JSON file, follow the below-mentioned steps exactly the same as the step creating the request. 

Since we need to send the noteID to the API, we need to update the noteID & add it to the path we are sending to the API using ‘/$id’ in put(), delete(), or post() method because we need to specify which note we are updating, deleting or sending respectively. We also need to re-fetch the notes once they are updated, deleted, or sent to display them.

1. Updating the data 

Dart




Future<Fruit> updateFruit(String title) async {
  final http.Response response = await http.put(
    'url/$id',
    headers: <String, String>{
      'Content-Type': 'application/json; charset=UTF-8',
    },
    body: jsonEncode(<String, String>{
      'title': title,
    }),
  );
  
  if (response.statusCode == 200) {
    return Fruit.fromJson(json.decode(response.body));
  } else {
    throw Exception('Failed to update album.');
  }
}

2. Deleting the data

Dart




Future<Fruit> deleteAlbum(int id) async {
  final http.Response response = await http.delete(
    'url/$id',
    headers: <String, String>{
      'Content-Type': 'application/json; charset=UTF-8',
    },
  );
  
  if (response.statusCode == 200) {
    return Fruit.fromJson(json.decode(response.body));
  } else {
    throw Exception('Failed to delete album.');
  }
}

3. Sending the data

Dart




Future<Fruit> sendFruit(
   
String title, int id, String imgUrl, int quantity) async {
     final http.Response response = await http.post(
     'url',
    headers: <String, String> {
      'Content-Type': 'application/json; charset=UTF-8',
    },
    body: jsonEncode(<String, String> {
      'title': title,
      'id': id.toString(),
      'imgUrl': imgUrl,
      'quantity': quantity.toString()
    }),
  );
  if (response.statusCode == 201) {
    return Fruit.fromJson(json.decode(response.body));
  } else {
    throw Exception('Failed to load album');
  }
}
Want a more fast-paced & competitive environment to learn the fundamentals of Android?
Click here to head to a guide uniquely curated by our experts with the aim to make you industry ready in no time!



My Personal Notes arrow_drop_up
Recommended Articles
Page :