Flutter Tutorial
Dart Programming
Flutter Basics
Flutter Widgets
- Flutter Scaffold
- Flutter Container
- Flutter Row and Column
- Flutter Text
- Flutter TextField
- Flutter Buttons
- Flutter Stack
- Flutter Forms
- Flutter Alert Dialogs
- Flutter Icons
- Flutter Images
- Flutter Card
- Flutter Tabbar
- Flutter Drawer
- Flutter Lists
- Flutter GridView
- Flutter Toast Notification
- Flutter Checkbox
- Flutter Radio Button
- Flutter Progress Bar
- Flutter Snackbar
- Flutter Tooltip
- Flutter Slider
- Flutter Switch
- Flutter Charts
- Flutter Bottom Navigation Bar
- Flutter Themes
- Flutter Table
- Flutter Calendar
- Flutter Animation
Flutter Routing
Advanced Concepts
Flutter Differences
Flutter Interview Questions
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.
try {
print(await client.get('https://www.javatpoint.com/'));
}
finally {
client.close();
}
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:
http: <latest_version>
You can import the http package as:
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
return http.get('https://jsonplaceholder.typicode.com/posts/1');
}
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:
final int id;
final String title;
final String body;
Post({this.userId, this.id, this.title, this. description});
factory Post.fromJson(Map<String, dynamic> json) {
return Post(
userId: json['userId'],
id: json['id'],
title: json['title'],
description: json['description'],
);
}
}
Now, you have to convert the http.response to a Post. The following code updates the fetchPost() function for returning a Future<Post>.
final response = await http.get( Give the link of JSON file');
if (response.statusCode == 200) {
// If the server returns an OK response, then parse the JSON.
return Post.fromJson(json.decode(response.body));
} else {
// If the response was umexpected, throw an error.
throw Exception('Failed to load post');
}
}
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.
Future<Post> post;
@override
void initState() {
super.initState();
post = fetchPost();
}
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.
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();
},
);
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.
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<MyApp> {
Future<Post> 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<Post>(
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<Post> 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<String, dynamic> 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"
}
]