Flutter API Calling Made Simple: Best Practices and Demos

MD. Sad Adnan
5 min readMar 5, 2023

--

Learn how to use HTTP, GET, POST, GET with Header, and POST with Header methods of API calling in Flutter, including creating models and best practices for beginners.

Photo by Stephen Dawson on Unsplash

Flutter has become a popular platform for building mobile applications because of its simplicity and flexibility. One of the crucial features of mobile applications is the ability to communicate with a server to fetch data or perform some action. This communication is done using APIs, which allow you to send and receive data in a structured format. In this article, we will discuss different methods of API calling in Flutter and best practices for beginners.

HTTP Requests in Flutter HTTP requests are used to communicate with a server through APIs. Flutter has an HTTP library that provides functions to make HTTP requests. The HTTP library in Flutter is based on the http package, which provides the following methods:

  1. GET method: This method is used to fetch data from a server.
  2. POST method: This method is used to send data to a server.
  3. PUT method: This method is used to update data on a server.
  4. DELETE method: This method is used to delete data from a server.
Photo by Fotis Fotopoulos on Unsplash

API Calling Methods in Flutter

  1. GET Method:

The GET method is used to retrieve data from the server. In Flutter, the GET method can be implemented using the http.get() method. The following code demonstrates how to implement the GET method in Flutter:

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

Future<dynamic> getData() async {
final response = await http.get(Uri.parse('https://api.example.com/data'));
if (response.statusCode == 200) {
return json.decode(response.body);
} else {
throw Exception('Failed to load data');
}
}

The above code will fetch data from the server and return it in JSON format. The json.decode() method is used to convert the JSON data to Dart objects.

2. POST Method:

The POST method is used to send data to the server. In Flutter, the POST method can be implemented using the http.post() method. The following code demonstrates how to implement the POST method in Flutter:

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

Future<dynamic> sendData(String name, String email) async {
final response = await http.post(Uri.parse('https://api.example.com/user'),
body: json.encode({'name': name, 'email': email}),
headers: {'Content-Type': 'application/json'});
if (response.statusCode == 200) {
return json.decode(response.body);
} else {
throw Exception('Failed to send data');
}
}

The above code will send data to the server in JSON format. The json.encode() method is used to convert the Dart objects to JSON format.

3. GET Method with Headers:

Sometimes, you may need to send some headers along with the GET request to the server. In Flutter, the GET method with headers can be implemented using the http.get() method with the headers parameter. The following code demonstrates how to implement the GET method with headers in Flutter:

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

Future<dynamic> getDataWithHeader(String token) async {
final response = await http.get(Uri.parse('https://api.example.com/data'),
headers: {'Authorization': 'Bearer $token'});
if (response.statusCode == 200) {
return json.decode(response.body);
} else {
throw Exception('Failed to load data');
}
}

The above code will fetch data from the server with the specified headers.

4. POST Method with Headers:

Sometimes, you may need to send some headers along with the POST request to the server. In Flutter, the POST method with headers can be implemented using the http.post() method with the headers parameter. The following code demonstrates how to implement the POST method with headers in Flutter:

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

Future<dynamic> sendDataWithHeader(String name, String email, String token) async {
final response = await http.post(Uri.parse('https://api.example.com/user'),
body: json.encode({'name': name, 'email': email}),
headers: {'Content-Type': 'application/json', 'Authorization': 'Bearer $token'});
if (response.statusCode == 200) {
return json.decode(response.body);
} else {
throw Exception('Failed to send data');
}
}

The above code will send data to the server in JSON format with the specified headers.

Photo by Christina @ wocintechchat.com on Unsplash

Creating Models in Flutter In Flutter:

it is common to create models to represent the data fetched from the server. A model is a class that contains fields to store data. When you fetch data from the server, you can convert the JSON data to model objects.

Here’s an example of a model class:

class User {
final String name;
final String email;

User({required this.name, required this.email});

factory User.fromJson(Map<String, dynamic> json) {
return User(
name: json['name'],
email: json['email'],
);
}
}

In the above code, we have created a User class with name and email fields. The fromJson() method is used to convert JSON data to a User object.

Best Practices for API Calling in Flutter

  1. Always handle errors: Whenever you make an API call, there is always a chance that it may fail. Always handle errors properly and show appropriate messages to the user.
  2. Use models to represent data: Use models to represent data fetched from the server. This makes it easier to work with data in your app.
  3. Use async/await: Use async/await when making API calls. This makes your code easier to read and understand.
  4. Use libraries: There are many libraries available in Flutter for making API calls. Use them instead of reinventing the wheel.
  5. Use constants: Define constants for URLs, headers, and other data that you use frequently. This makes it easier to update them if needed.

Conclusion API calling is an essential part of mobile application development. In this article, we have discussed different methods of API calling in Flutter and best practices for beginners. We have also shown examples of how to implement these methods in Flutter with code snippets. By following these best practices, you can make your code more robust and efficient. Happy coding!

--

--

MD. Sad Adnan
MD. Sad Adnan

Written by MD. Sad Adnan

Love Programming, Developing Solutions of Real Life Problems and Reading Books.

Responses (3)