{"id":2123,"date":"2022-04-08T06:14:42","date_gmt":"2022-04-08T06:14:42","guid":{"rendered":"https:\/\/mdr.foobrdigital.com\/?p=2123"},"modified":"2022-04-08T06:14:42","modified_gmt":"2022-04-08T06:14:42","slug":"flutter-rest-api","status":"publish","type":"post","link":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/2022\/04\/08\/flutter-rest-api\/","title":{"rendered":"Flutter REST API"},"content":{"rendered":"\n<p>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.<\/p>\n\n\n\n<p>Flutter provides&nbsp;<strong>http package<\/strong>&nbsp;to use http resources. The http package uses&nbsp;<strong>await<\/strong>&nbsp;and&nbsp;<strong>async<\/strong>&nbsp;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.<\/p>\n\n\n\n<p>The detail explanation of the core methods of the http package are as follows:<\/p>\n\n\n\n<p><strong>Read:<\/strong>&nbsp;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&lt;String&gt;.<\/p>\n\n\n\n<p><strong>Get:<\/strong>&nbsp;This method requests the specified url from the get method and returns a response as Future&lt;response&gt;. Here, the response is a class, which holds the response information.<\/p>\n\n\n\n<p><strong>Post:<\/strong>&nbsp;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&lt;response&gt;.<\/p>\n\n\n\n<p><strong>Put:<\/strong>&nbsp;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&lt;response<strong>&gt;<\/strong>.<\/p>\n\n\n\n<p><strong>Head:<\/strong>&nbsp;It is similar to the Get method, but without the response body.<\/p>\n\n\n\n<p><strong>Delete:<\/strong>&nbsp;This method is used to remove all the specified resources.<\/p>\n\n\n\n<p>The http package also provides a standard&nbsp;<strong>http client class<\/strong>&nbsp;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&nbsp;<strong>close<\/strong>() method. Otherwise, it works as an http class. The following code explains it more clearly.<a href=\"https:\/\/www.javatpoint.com\/flutter-rest-api#\"><\/a><a href=\"https:\/\/www.javatpoint.com\/flutter-rest-api#\"><\/a><a href=\"https:\/\/www.javatpoint.com\/flutter-rest-api#\"><\/a><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>var client = new http.Client();   \ntry {   \n   print(await client.get('https:\/\/www.javatpoint.com\/'));   \n}   \nfinally {   \n   client.close();   \n}  <\/code><\/pre>\n\n\n\n<p>To&nbsp;<strong>fetch<\/strong>&nbsp;data from the internet, you need to follow these necessary steps:<\/p>\n\n\n\n<p><strong>Step 1:<\/strong>&nbsp;Install the latest http package and add it to the project.<\/p>\n\n\n\n<p>To install the http package, open the\u00a0<strong>pubspec.yaml<\/strong>\u00a0file in your project folder and add http package in the\u00a0<strong>dependency<\/strong>\u00a0section. You can get the latest http package\u00a0here\u00a0and add it like:<a href=\"https:\/\/www.javatpoint.com\/flutter-rest-api#\"><\/a><a href=\"https:\/\/www.javatpoint.com\/flutter-rest-api#\"><\/a><a href=\"https:\/\/www.javatpoint.com\/flutter-rest-api#\"><\/a><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>dependencies:  \n  http: &lt;latest_version>  <\/code><\/pre>\n\n\n\n<p>You can&nbsp;<strong>import<\/strong>&nbsp;the http package as:<a href=\"https:\/\/www.javatpoint.com\/flutter-rest-api#\"><\/a><a href=\"https:\/\/www.javatpoint.com\/flutter-rest-api#\"><\/a><a href=\"https:\/\/www.javatpoint.com\/flutter-rest-api#\"><\/a><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import 'package:http\/http.dart' as http;  <\/code><\/pre>\n\n\n\n<p><strong>Step 2:<\/strong>&nbsp;Next, make a network request by using the http package.<\/p>\n\n\n\n<p>In this step, you need to make a network request by using the&nbsp;<strong>http.get()<\/strong>&nbsp;method<a href=\"https:\/\/www.javatpoint.com\/flutter-rest-api#\"><\/a><a href=\"https:\/\/www.javatpoint.com\/flutter-rest-api#\"><\/a><a href=\"https:\/\/www.javatpoint.com\/flutter-rest-api#\"><\/a><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Future&lt;http.Response> fetchPost() {  \n  return http.get('https:\/\/jsonplaceholder.typicode.com\/posts\/1');  \n}  <\/code><\/pre>\n\n\n\n<p>In the above code, the&nbsp;<strong>Future<\/strong>&nbsp;is a class that contains an object. The object represents a potential value or error.<\/p>\n\n\n\n<p><strong>Step 3:<\/strong>&nbsp;Now, convert the response getting from network request into a custom Dart object.<\/p>\n\n\n\n<p>First, you need to create a&nbsp;<strong>Post class<\/strong>. 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:<a href=\"https:\/\/www.javatpoint.com\/flutter-rest-api#\"><\/a><a href=\"https:\/\/www.javatpoint.com\/flutter-rest-api#\"><\/a><a href=\"https:\/\/www.javatpoint.com\/flutter-rest-api#\"><\/a><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class Post {  \n  final int userId;  \n  final int id;  \n  final String title;  \n  final String body;  \n  \n  Post({this.userId, this.id, this.title, this. description});  \n  \n  factory Post.fromJson(Map&lt;String, dynamic> json) {  \n    return Post(  \n      userId: json&#91;'userId'],  \n      id: json&#91;'id'],  \n      title: json&#91;'title'],  \n      description: json&#91;'description'],  \n    );  \n  }  \n}  <\/code><\/pre>\n\n\n\n<p>Now, you have to convert the&nbsp;<strong>http.response<\/strong>&nbsp;to a Post. The following code updates the&nbsp;<strong>fetchPost()&nbsp;<\/strong>function for returning a Future&lt;Post&gt;.<a href=\"https:\/\/www.javatpoint.com\/flutter-rest-api#\"><\/a><a href=\"https:\/\/www.javatpoint.com\/flutter-rest-api#\"><\/a><a href=\"https:\/\/www.javatpoint.com\/flutter-rest-api#\"><\/a><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Future&lt;Post> fetchPost() async {  \n  final response = await http.get( Give the link of JSON file');  \n  \n  if (response.statusCode == 200) {  \n    \/\/ If the server returns an OK response, then parse the JSON.  \n    return Post.fromJson(json.decode(response.body));  \n  } else {  \n    \/\/ If the response was umexpected, throw an error.  \n    throw Exception('Failed to load post');  \n  }  \n}  <\/code><\/pre>\n\n\n\n<p><strong>Step 4:<\/strong>&nbsp;Now, fetch the data with Flutter. You can call the fetch method in the&nbsp;<strong>initState()<\/strong>. The following code explains how you can fetch the data.<a href=\"https:\/\/www.javatpoint.com\/flutter-rest-api#\"><\/a><a href=\"https:\/\/www.javatpoint.com\/flutter-rest-api#\"><\/a><a href=\"https:\/\/www.javatpoint.com\/flutter-rest-api#\"><\/a><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class _MyAppState extends State&lt;MyApp> {  \n  Future&lt;Post> post;  \n  \n  @override  \n  void initState() {  \n    super.initState();  \n    post = fetchPost();  \n  }  <\/code><\/pre>\n\n\n\n<p><strong>Step 5:<\/strong>&nbsp;Finally, display the data. You can display the data by using the&nbsp;<strong>FutureBuilder<\/strong>&nbsp;widget. This widget can work easily with async data sources.<a href=\"https:\/\/www.javatpoint.com\/flutter-rest-api#\"><\/a><a href=\"https:\/\/www.javatpoint.com\/flutter-rest-api#\"><\/a><a href=\"https:\/\/www.javatpoint.com\/flutter-rest-api#\"><\/a><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>FutureBuilder&lt;Post&gt;(  \n  future: post,  \n  builder: (context, abc) {  \n    if (abc.hasData) {  \n      return Text(abc.data.title);  \n    } else if (abc.hasError) {  \n      return Text(\"${abc.error}\");  \n    }  \n  \n    \/\/ By default, it show a loading spinner.  \n    return CircularProgressIndicator();  \n  },  \n);  <\/code><\/pre>\n\n\n\n<p>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&nbsp;here.<a href=\"https:\/\/www.javatpoint.com\/flutter-rest-api#\"><\/a><a href=\"https:\/\/www.javatpoint.com\/flutter-rest-api#\"><\/a><a href=\"https:\/\/www.javatpoint.com\/flutter-rest-api#\"><\/a><span style=\"font-family: var(--list--font-family); background-color: var(--global--color-background); color: var(--global--color-primary); font-size: var(--global--font-size-base);\">&nbsp;<\/span><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import 'dart:async';  \nimport 'dart:convert';  \n  \nimport 'package:flutter\/material.dart';  \nimport 'package:http\/http.dart' as http;  \n  \nvoid main() =&gt; runApp(MyApp());  \n  \nclass MyApp extends StatefulWidget {  \n  MyApp({Key key}) : super(key: key);  \n  \n  @override  \n  _MyAppState createState() =&gt; _MyAppState();  \n}  \n  \nclass _MyAppState extends State&lt;MyApp&gt; {  \nFuture&lt;Post&gt; post;  \n  \n  @override  \n  void initState() {  \n    super.initState();  \n    post = fetchPost();  \n  }  \n  \n  @override  \n  Widget build(BuildContext context) {  \n    return MaterialApp(  \n      title: 'Flutter REST API Example',  \n      theme: ThemeData(  \n        primarySwatch: Colors.green,  \n      ),  \n      home: Scaffold(  \n        appBar: AppBar(  \n          title: Text('Flutter REST API Example'),  \n        ),  \n        body: Center(  \n          child: FutureBuilder&lt;Post&gt;(  \n            future: post,  \n            builder: (context, abc) {  \n              if (abc.hasData) {  \n                return Text(abc.data.title);  \n              } else if (abc.hasError) {  \n                return Text(\"${abc.error}\");  \n              }  \n  \n              \/\/ By default, it show a loading spinner.  \n              return CircularProgressIndicator();  \n            },  \n          ),  \n        ),  \n      ),  \n    );  \n  }  \n}  \n  \nFuture&lt;Post&gt; fetchPost() async {  \n  final response = await http.get('Give your JSON file web link.');  \n  \n  if (response.statusCode == 200) {  \n    \/\/ If the call to the server was successful (returns OK), parse the JSON.  \n    return Post.fromJson(json.decode(response.body));  \n  } else {  \n    \/\/ If that call was not successful (response was unexpected), it throw an error.  \n    throw Exception('Failed to load post');  \n  }  \n}  \n  \nclass Post {  \n  final int userId;  \n  final int id;  \n  final String title;  \n  final String description;  \n  \n  Post({this.userId, this.id, this.title, this. description});  \n  \n  factory Post.fromJson(Map&lt;String, dynamic&gt; json) {  \n    return Post(  \n      userId: json&#91;'userId'],  \n      id: json&#91;'id'],  \n      title: json&#91;'title'],  \n      description: json&#91;' description'],  \n    );  \n  }  \n} <\/code><\/pre>\n\n\n\n<p>The JSON file is shown below.<a href=\"https:\/\/www.javatpoint.com\/flutter-rest-api#\"><\/a><a href=\"https:\/\/www.javatpoint.com\/flutter-rest-api#\"><\/a><a href=\"https:\/\/www.javatpoint.com\/flutter-rest-api#\"><\/a><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&#91;   \n   {   \n      \"userId\": 01,   \n      \"id\": 1,   \n      \"title\": \"iPhone\",   \n      \"description\": \"iPhone is the very stylist phone ever\"  \n   },   \n   {   \n      \"userId\": 02,   \n      \"id\": 2,   \n      \"title\": \"Pixel\",   \n      \"description\": \"Pixel is the most feature phone ever\"  \n   },   \n   {   \n      \"userId\": 03,   \n      \"id\": 3,   \n      \"title\": \"Laptop\",   \n      \"description\": \"Laptop is most popular development tool\"  \n   },   \n   {   \n      \"userId\": 04,   \n      \"id\": 4,   \n      \"title\": \"Tablet\",   \n      \"description\": \"Tablet is the most useful device used for meeting\"   \n   }  \n]<\/code><\/pre>\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>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&nbsp;http package&nbsp;to use http resources. The [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[599],"tags":[],"_links":{"self":[{"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/posts\/2123"}],"collection":[{"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/comments?post=2123"}],"version-history":[{"count":0,"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/posts\/2123\/revisions"}],"wp:attachment":[{"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/media?parent=2123"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/categories?post=2123"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/tags?post=2123"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}