Retrofit in Flutter

Tamil KannanCV
2 min readMay 22, 2023

--

Making internet requests using Retrofit in Flutter made easier. I gonna show you how to do that.

What is Retrofit?

Retrofit is a type-safe REST client for Android (Java and Kotlin) to make it easier to consume the RESTful web services.

Let’s see how to implement Retrofit in Flutter.

Add the following dependency in your pubspec.yaml file.

dependencies:
dio: ^5.1.2
retrofit: '>=4.0.0 <5.0.0'
logger: any #for logging purpose

dev_dependencies:
retrofit_generator: '>=5.0.0 <6.0.0'
build_runner: '>=2.3.0 <4.0.0'
json_serializable: ^4.4.0

Then create a file named rest_client.dart for our client class.

import 'package:json_annotation/json_annotation.dart';
import 'package:retrofit/retrofit.dart';
import 'package:dio/dio.dart';

part 'rest_client.g.dart';

@RestApi(baseUrl: "htps://5d42a6e2bc64f90014a56ca0.mockapi.io/api/v1/")
abstract class RestClient {
factory RestClient(Dio dio, {String baseUrl}) = _RestClient;

@GET("/tasks")
Future<List<Task>> getTasks();
}

@JsonSerializable()
class Task {
String? id;
String? name;
String? avatar;
String? createdAt;

Task({this.id, this.name, this.avatar, this.createdAt});

factory Task.fromJson(Map<String, dynamic> json) => _$TaskFromJson(json);
Map<String, dynamic> toJson() => _$TaskToJson(this);
}

Here we are using dio for sending and getting requests. For sending a get request we simply use @GET along with its path, similarly for others,

  • GET request → @GET(<path>)
  • POST request → @POST(<path>)
  • PUT request → @PUT(<path>) and so on…

It automatically maps the returned data into the data type mentioned in the function return type. We can use @Query("id") for adding query and @Body() for adding body.

We need to run the following commands after creating the client class.

dart run build_runner build

This command will generate a new file named rest_client.g.dart with the generated code that implements the requests.

There are various useful things that can be done using retrofit, you can find them in the pub.dev.

For more useful packages and informations on Flutter, follow me and put your likes and comments.

Thank you!

--

--