Flutter REST API

In this section, we learn how we can access the REST API in a Flutter app. Today, most of the apps use remote data using APIs to get the data from the internet.

Flutter provides http packages1 for using http resources. This is used to await and async features and provide many high-level methods such as read, get, post, put, head, and delete methods for sending and getting the data from remote locations.

The detail explanation of some of the main methods of the http package as shown below:

Read: It is used for reading or retrieving the representation of the resources. It requests the url by GET method and returns the response as Future.

Get: This method requests the specified url using the GET method and returns a response as Future.

Post: This method is used for submitting the data for the specified resources. It requests the url by posting the data and returning a response Future.

Put: This method is for updating the capabilities. This updates all the current representation of the target resource with the payloads. This method requests the url and returns a response as Future.

Head: This is similar to the Get method, but without the body.

Delete: This method is used for removing all the specified resources.

It also provides a standard http client class that supports the persistent connection. This class is useful when a lot of requests are made to the same server. This should be closed properly using the close() method.

var client = new http.Client();   
try {   
   print(await client.get('https://www.javatpoint.com/'));   
}   
finally {   
   client.close();   
}  

Let us see the complete code example to understand how Flutter works with REST API to fetch data from the network.

import 'dart:async';  
import 'dart:convert';  
  
import 'package:flutter/material.dart';  
import 'package:http/http.dart' as http;  
  
void main() => runApp(MyApp());  
  
class MyApp extends StatefulWidget {  
  MyApp({Key key}) : super(key: key);  
  
  @override  
  _MyAppState createState() => _MyAppState();  
}  
  
class _MyAppState extends State {  
Future post;  
  
  @override  
  void initState() {  
    super.initState();  
    post = fetchPost();  
  }  
  
  @override  
  Widget build(BuildContext context) {  
    return MaterialApp(  
      title: 'Flutter REST API Example',  
      theme: ThemeData(  
        primarySwatch: Colors.green,  
      ),  
      home: Scaffold(  
        appBar: AppBar(  
          title: Text('Flutter REST API Example'),  
        ),  
        body: Center(  
          child: FutureBuilder(  
            future: post,  
            builder: (context, abc) {  
              if (abc.hasData) {  
                return Text(abc.data.title);  
              } else if (abc.hasError) {  
                return Text("${abc.error}");  
              }  
  
              // By default, it show a loading spinner.  
              return CircularProgressIndicator();  
            },  
          ),  
        ),  
      ),  
    );  
  }  
}  
  
Future fetchPost() async {  
  final response = await http.get('Give your JSON file web link.');  
  
  if (response.statusCode == 200) {  
    // If the call to the server was successful (returns OK), parse the JSON.  
    return Post.fromJson(json.decode(response.body));  
  } else {  
    // If that call was not successful (response was unexpected), it throw an error.  
    throw Exception('Failed to load post');  
  }  
}  
  
class Post {  
  final int userId;  
  final int id;  
  final String title;  
  final String description;  
  
  Post({this.userId, this.id, this.title, this. description});  
  
  factory Post.fromJson(Map json) {  
    return Post(  
      userId: json['userId'],  
      id: json['id'],  
      title: json['title'],  
      description: json[' description'],  
    );  
  }  
}
The JSON file is shown below.
[   
   {   
      "userId": 01,   
      "id": 1,   
      "title": "iPhone",   
      "description": "iPhone is the very stylist phone ever"  
   },   
   {   
      "userId": 02,   
      "id": 2,   
      "title": "Pixel",   
      "description": "Pixel is the most feature phone ever"  
   },   
   {   
      "userId": 03,   
      "id": 3,   
      "title": "Laptop",   
      "description": "Laptop is most popular development tool"  
   },   
   {   
      "userId": 04,   
      "id": 4,   
      "title": "Tablet",   
      "description": "Tablet is the most useful device used for meeting"   
   }  
] 
Subscribe Now