Flutter REST API

 

Flutter REST API

In this section, we are going to learn how we can access the REST API in the Flutter app. Today, most of the apps use remote data using APIs. So, this section will be the important part for those developers who want to make their carrier in Flutter.

Flutter provides http package to use http resources. The http package uses await and async features and provides many high-level methods such as read, get, post, put, head, and delete methods for sending and receiving data from remote locations. These methods simplify the development of REST-based mobile applications.

The detail explanation of the core methods of the http package are as follows:

Read: This method is used to read or retrieve the representation of resources. It requests the specified url by using the get method and returns the response as Future<String>.

Get: This method requests the specified url from the get method and returns a response as Future<response>. Here, the response is a class, which holds the response information.

Post: This method is used to submit the data to the specified resources. It requests the specified url by posting the given data and return a response as Future<response>.

Put: This method is utilized for update capabilities. It updates all the current representation of the target resource with the request payloads. This method request the specified url and returns a response as Future<response>.

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

Delete: This method is used to remove all the specified resources.

The http package also provides a standard http client class that supports the persistent connection. This class is useful when a lot of requests to be made on a particular server. It should be closed properly using the close() method. Otherwise, it works as an http class. The following code explains it more clearly.

  1. var client = new http.Client();   
  2. try {   
  3.    print(await client.get('https://www.javatpoint.com/'));   
  4. }   
  5. finally {   
  6.    client.close();   
  7. }  

To fetch data from the internet, you need to follow these necessary steps:

Step 1: Install the latest http package and add it to the project.

To install the http package, open the pubspec.yaml file in your project folder and add http package in the dependency section. You can get the latest http package here and add it like:

  1. dependencies:  
  2.   http: <latest_version>  

You can import the http package as:

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

Step 2: Next, make a network request by using the http package.

In this step, you need to make a network request by using the http.get() method

  1. Future<http.Response> fetchPost() {  
  2.   return http.get('https://jsonplaceholder.typicode.com/posts/1');  
  3. }  

In the above code, the Future is a class that contains an object. The object represents a potential value or error.

Step 3: Now, convert the response getting from network request into a custom Dart object.

First, you need to create a Post class. The Post class received data from the network request and includes a factory constructor, which creates Post from JSON. You can create a Post class as below:

  1. class Post {  
  2.   final int userId;  
  3.   final int id;  
  4.   final String title;  
  5.   final String body;  
  6.   
  7.   Post({this.userId, this.id, this.title, this. description});  
  8.   
  9.   factory Post.fromJson(Map<String, dynamic> json) {  
  10.     return Post(  
  11.       userId: json['userId'],  
  12.       id: json['id'],  
  13.       title: json['title'],  
  14.       description: json['description'],  
  15.     );  
  16.   }  
  17. }  

Now, you have to convert the http.response to a Post. The following code updates the fetchPost() function for returning a Future<Post>.

  1. Future<Post> fetchPost() async {  
  2.   final response = await http.get( Give the link of JSON file');  
  3.   
  4.   if (response.statusCode == 200) {  
  5.     // If the server returns an OK response, then parse the JSON.  
  6.     return Post.fromJson(json.decode(response.body));  
  7.   } else {  
  8.     // If the response was umexpected, throw an error.  
  9.     throw Exception('Failed to load post');  
  10.   }  
  11. }  

Step 4: Now, fetch the data with Flutter. You can call the fetch method in the initState(). The following code explains how you can fetch the data.

  1. class _MyAppState extends State<MyApp> {  
  2.   Future<Post> post;  
  3.   
  4.   @override  
  5.   void initState() {  
  6.     super.initState();  
  7.     post = fetchPost();  
  8.   }  

Step 5: Finally, display the data. You can display the data by using the FutureBuilder widget. This widget can work easily with async data sources.

  1. FutureBuilder<Post>(  
  2.   future: post,  
  3.   builder: (context, abc) {  
  4.     if (abc.hasData) {  
  5.       return Text(abc.data.title);  
  6.     } else if (abc.hasError) {  
  7.       return Text("${abc.error}");  
  8.     }  
  9.   
  10.     // By default, it show a loading spinner.  
  11.     return CircularProgressIndicator();  
  12.   },  
  13. );  

Let us see the complete code to understand how Flutter works with REST API to fetch data from the network. You can learn more in detail from here.

  1. import 'dart:async';  
  2. import 'dart:convert';  
  3.   
  4. import 'package:flutter/material.dart';  
  5. import 'package:http/http.dart' as http;  
  6.   
  7. void main() => runApp(MyApp());  
  8.   
  9. class MyApp extends StatefulWidget {  
  10.   MyApp({Key key}) : super(key: key);  
  11.   
  12.   @override  
  13.   _MyAppState createState() => _MyAppState();  
  14. }  
  15.   
  16. class _MyAppState extends State<MyApp> {  
  17. Future<Post> post;  
  18.   
  19.   @override  
  20.   void initState() {  
  21.     super.initState();  
  22.     post = fetchPost();  
  23.   }  
  24.   
  25.   @override  
  26.   Widget build(BuildContext context) {  
  27.     return MaterialApp(  
  28.       title: 'Flutter REST API Example',  
  29.       theme: ThemeData(  
  30.         primarySwatch: Colors.green,  
  31.       ),  
  32.       home: Scaffold(  
  33.         appBar: AppBar(  
  34.           title: Text('Flutter REST API Example'),  
  35.         ),  
  36.         body: Center(  
  37.           child: FutureBuilder<Post>(  
  38.             future: post,  
  39.             builder: (context, abc) {  
  40.               if (abc.hasData) {  
  41.                 return Text(abc.data.title);  
  42.               } else if (abc.hasError) {  
  43.                 return Text("${abc.error}");  
  44.               }  
  45.   
  46.               // By default, it show a loading spinner.  
  47.               return CircularProgressIndicator();  
  48.             },  
  49.           ),  
  50.         ),  
  51.       ),  
  52.     );  
  53.   }  
  54. }  
  55.   
  56. Future<Post> fetchPost() async {  
  57.   final response = await http.get('Give your JSON file web link.');  
  58.   
  59.   if (response.statusCode == 200) {  
  60.     // If the call to the server was successful (returns OK), parse the JSON.  
  61.     return Post.fromJson(json.decode(response.body));  
  62.   } else {  
  63.     // If that call was not successful (response was unexpected), it throw an error.  
  64.     throw Exception('Failed to load post');  
  65.   }  
  66. }  
  67.   
  68. class Post {  
  69.   final int userId;  
  70.   final int id;  
  71.   final String title;  
  72.   final String description;  
  73.   
  74.   Post({this.userId, this.id, this.title, this. description});  
  75.   
  76.   factory Post.fromJson(Map<String, dynamic> json) {  
  77.     return Post(  
  78.       userId: json['userId'],  
  79.       id: json['id'],  
  80.       title: json['title'],  
  81.       description: json[' description'],  
  82.     );  
  83.   }  
  84. }  

The JSON file is shown below.

  1. [   
  2.    {   
  3.       "userId"01,   
  4.       "id"1,   
  5.       "title""iPhone",   
  6.       "description""iPhone is the very stylist phone ever"  
  7.    },   
  8.    {   
  9.       "userId"02,   
  10.       "id"2,   
  11.       "title""Pixel",   
  12.       "description""Pixel is the most feature phone ever"  
  13.    },   
  14.    {   
  15.       "userId"03,   
  16.       "id"3,   
  17.       "title""Laptop",   
  18.       "description""Laptop is most popular development tool"  
  19.    },   
  20.    {   
  21.       "userId"04,   
  22.       "id"4,   
  23.       "title""Tablet",   
  24.       "description""Tablet is the most useful device used for meeting"   
  25.    }  
  26. ]  


Post a Comment

Previous Post Next Post