Table of contents
No headings in the article.
API is the acronym for Application Programming Interface, which is a software intermediary that allows two applications to talk to each other. For example, each time you use an app like Facebook, send an instant message, or check the weather on your phone, you’re using an API.
API is a broad term while REST API is a specialized API. REST stands for Representational State Transfer.
A REST API is a web service API which uses URIs and HTTP protocol and JSON for data format.
In this article, we are going to learn how to use the Retrofit library for auto code generation in Flutter.
So let’s get started.
Step 1: Create a new Flutter Application
Step 2: Add the following dependencies below in your pubspec.yaml file.
dependencies:
retrofit: ^3.0.0
dio: ^4.0.4
built_value: ^8.1.3
json_annotation: ^4.4.0
dev_dependencies:
retrofit_generator: ^3.0.0+2
build_runner: ^2.1.5
json_serializable: ^6.1.1
built_value_generator: ^8.1.3
Step 2a: Add the INTERNET permission (Android).
To use the internet in android, open the AndroidManifest.xml and add the internet permission.
<uses-permission android:name="android.permission.INTERNET" />
Step 3: To demonstrate API calling in this article, we are going to use this public API: jsonplaceholder.typicode.com/posts
Next we create a new dart file called api_request.dart
In the api_request.dart file:
Import the packages, and create a part file. You will encounter an error with the part file line, continue it will be resolved soon.
Part file allows you to split a file into multiple dart files.
import 'package:dio/dio.dart';
import 'package:json_annotation/json_annotation.dart';
import 'package:retrofit/retrofit.dart';
part 'api_request.g.dart';
Still in api_request.dart, create an abstract class RestClient
@RestApi(baseUrl: "https://jsonplaceholder.typicode.com/posts")
abstract class RestClient {
factory RestClient(Dio dio, {String baseUrl}) = _RestClient;
@GET("")
Future<List<FetchPost>> getPost();
}
RestClient class is responsible for handling all the network call methods. In the above code, it will show an error on the _RestClient variable, which will be resolved with steps we see later on in this article.
Next, will we convert the “JSON” response to the “FetchPost” class using Retrofit.
The code below will do auto serialization of the JSON data.
@JsonSerializable()
class FetchPost {
int userId;
int id;
String title;
String body;
FetchPost({required this.userId, required this.id, required this.title, required this.body});
factory FetchPost.fromJson(Map<String, dynamic> json) => _$FetchPostFromJson(json);
Map<String, dynamic> toJson() => _$FetchPostToJson(this);
}
At this time it will show errors. So let’s run the command below to generate the part ‘api_request.g.dart’;
Run the command: flutter pub run build_runner build in the terminal
Step 4: Displaying the Data in main.dart
Declare a variable called client in the widget build method
final client = RestClient(
Dio(BaseOptions(contentType: "application/json")));
In the Scaffold body, copy the code below to call the API with retrofit object.
FutureBuilder<List<FetchPost>>(
future: client.getPost(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return ListView.builder(
itemCount: snapshot.data!.length,
// ignore: avoid_unnecessary_containers
itemBuilder: (_, index) =>
Container(
child: Container(
margin: const EdgeInsets.symmetric(
horizontal: 10, vertical: 5),
padding: const EdgeInsets.all(20.0),
decoration: BoxDecoration(
color: const Color(0xffFFA500),
borderRadius: BorderRadius.circular(15.0),
),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"${snapshot.data![index].id}",
style: const TextStyle(
fontSize: 18.0,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 10),
Text("${snapshot.data![index].body}"),
],
),
),
),
);
} else {
return const Center(child: CircularProgressIndicator());
}
},
)
The End ! 😊
You can find the source code of this post in the following Github repository: github.com/Syntax007/retrofit_tutorial
Please give some 👏 if you like what you read and follow me to stay updated with my latest posts. Gracias! 😊