Implementing Rest API in Flutter - GeeksforGeeks

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.
Install the http dependency and add it in pubspec.yaml file in order to use API in the application.
dependencies:
  http:

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";

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']);  }}
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}"),                          ],                        )))              ]),        ));  }}
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]);      },    );  }}
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:
Following is the UI screen of the homepage of Flutter application with decoded JSON data.
Output:
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.
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.');  }}
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.');  }}
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');  }}
android
Flutter
Dart
Flutter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Flutter - DropDownButton Widget
Flutter - Custom Bottom Navigation Bar
Flutter - Checkbox Widget
ListView Class in Flutter
Flutter - Flexible Widget
Flutter - DropDownButton Widget
Flutter - Custom Bottom Navigation Bar
Flutter - Checkbox Widget
Flutter Tutorial
Flutter - Flexible Widget