Retrofit For Dart

retrofit retrofit_generator Pub Likes Testing

retrofit.dart is a type conversion dio client generator using source_gen and inspired by Chopper and Retrofit.



Add the generator to your dev dependencies

  retrofit: '>=4.0.0 <5.0.0'
  logger: any  #for logging purpose
  json_annotation: ^4.8.1

  retrofit_generator: '>=7.0.0 <8.0.0'   // required dart >=2.19
  build_runner: '>=2.3.0 <4.0.0'
  json_serializable: ^6.6.2

Define and Generate your API

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

part 'example.g.dart';

@RestApi(baseUrl: '')
abstract class RestClient {
  factory RestClient(Dio dio, {String baseUrl}) = _RestClient;

  Future<List<Task>> getTasks();

class Task {
  const Task({,, this.avatar, this.createdAt});

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

  final String? id;
  final String? name;
  final String? avatar;
  final String? createdAt;

  Map<String, dynamic> toJson() => _$TaskToJson(this);

then run the generator

# dart
dart pub run build_runner build

# flutter	
flutter pub run build_runner build

Use it

import 'package:dio/dio.dart';
import 'package:logger/logger.dart';
import 'package:retrofit_example/example.dart';

final logger = Logger();

void main(List<String> args) {
  final dio = Dio(); // Provide a dio instance
  dio.options.headers['Demo-Header'] = 'demo header'; // config your dio headers globally
  final client = RestClient(dio);

  client.getTasks().then((it) => logger.i(it));


Type Conversion

Before you use the type conversion, please make sure that a factory Task.fromJson(Map<String, dynamic> json) must be provided for each model class. json_serializable is recommended to be used as the serialization tool.

Future<List<Task>> getTasks();

class Task {
  const Task({required});

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

  final String name;

HTTP Methods

The HTTP methods in the below sample are supported.

  Future<Task> getTask(@Path('id') String id);
  Future<String> queries(@Queries() Map<String, dynamic> queries);
  Future<String> namedExample(
      @Query('apikey') String apiKey,
      @Query('scope') String scope,
      @Query('type') String type,
      @Query('from') int from);
  Future<Task> updateTaskPart(
      @Path() String id, @Body() Map<String, dynamic> map);
  Future<Task> updateTask(@Path() String id, @Body() Task task);
  Future<void> deleteTask(@Path() String id);
  Future<Task> createTask(@Body() Task task);
  Future<void> createNewTaskFromFile(@Part() File file);
  Future<String> postUrlEncodedFormData(@Field() String hello);

Get original HTTP response

  Future<HttpResponse<Task>> getTask(@Path('id') String id);

  Future<HttpResponse<List<Task>>> getTasks();

HTTP Header

  • Add a HTTP header from the parameter of the method
  Future<Task> getTasks(@Header('Content-Type') String contentType);
  • Add static HTTP headers
  import 'package:dio/dio.dart' hide Headers;

  // ...
  @Headers(<String, dynamic>{
    'Content-Type': 'application/json',
    'Custom-Header': 'Your header',
  Future<Task> getTasks();

Error Handling

catchError(Object) should be used for capturing the exception and failed response. You can get the detailed response info from DioError.response.

client.getTask('2').then((it) {
}).catchError((obj) {
  // non-200 error goes here.
  switch (obj.runtimeType) {
    case DioError:
      // Here's the sample to get the failed response error code and message
      final res = (obj as DioError).response;
      logger.e('Got error : ${res.statusCode} -> ${res.statusMessage}');

Relative API baseUrl

If you want to use a relative baseUrl value in the RestApi annotation of the RestClient, you need to specify a baseUrl in dio.options.baseUrl.

@RestApi(baseUrl: '/tasks')
abstract class RestClient {
  factory RestClient(Dio dio, {String baseUrl}) = _RestClient;

  Future<HttpResponse<Task>> getTask(@Path('id') String id);

  Future<HttpResponse<List<Task>>> getTasks();

dio.options.baseUrl = '';
final client = RestClient(dio);

Multiple endpoints support

If you want to use multiple endpoints to your RestClient, you should pass your base url when you initiate RestClient. Any value defined in RestApi will be ignored.

@RestApi(baseUrl: 'this url will be ignored if baseUrl is passed')
abstract class RestClient {
  factory RestClient(Dio dio, {String baseUrl}) = _RestClient;

final client = RestClient(dio, baseUrl: 'your base url');

If you want to use the base url from dio.option.baseUrl, which has lowest priority, please don't pass any parameter to RestApi annotation and RestClient's structure method.

Multithreading (Flutter only)

If you want to parse models on a separate thread, you can take advantage of the compute function, just like Dio does when converting String data responses into json objects.

For each model that you use you will need to define 2 top-level functions:

FutureOr<Task> deserializeTask(Map<String, dynamic> json);
FutureOr<dynamic> serializeTask(Task object);

If you want to handle lists of objects, either as return types or parameters, you should provide List counterparts:

FutureOr<List<Task>> deserializeTaskList(Map<String, dynamic> json);
FutureOr<dynamic> serializeTaskList(List<Task> objects);

Finally, make sure you set your @RestApi to use the Parser.FlutterCompute parser:

@RestApi(parser: Parser.FlutterCompute)


  baseUrl: '',
  parser: Parser.FlutterCompute,
abstract class RestClient {
  factory RestClient(Dio dio, {String baseUrl}) = _RestClient;

  Future<Task> getTask();

  Future<List<Task>> getTasks();

  Future<void> updateTasks(Task task);

  Future<void> updateTasks(List<Task> tasks);

Task deserializeTask(Map<String, dynamic> json) => Task.fromJson(json);

List<Task> deserializeTaskList(List<Map<String, dynamic>> json) => => Task.fromJson(e)).toList();

Map<String, dynamic> serializeTask(Task object) => object.toJson();

List<Map<String, dynamic>> serializeTaskList(List<Task> objects) => => e.toJson()).toList();

N.B. Avoid using Map values, otherwise multiple background isolates will be spawned to perform the computation, which is extremely intensive for Dart.

abstract class RestClient {
  factory RestClient(Dio dio, {String baseUrl}) = _RestClient;

  // BAD
  Future<Map<String, Task>> getTasks();

  Future<void> updateTasks(Map<String, Task> tasks);

  // GOOD
  Future<TaskNames> getTaskNames();

  Future<void> updateTasks(TaskNames tasks);

TaskNames deserializeTaskNames(Map<String, dynamic> json) =>

class TaskNames {
  const TaskNames({required this.taskNames});

  final Map<String, Task> taskNames;

  factory TaskNames.fromJson(Map<String, dynamic> json) =>

Hide generated files

For the project not to be confused with the files generated by the retrofit you can hide them.

Android studio

File -> Settings -> Editor -> File Types

Add "ignore files and folders"



  • JetBrains. Thanks for providing the great IDE tools.

Contributors ✨

Thanks goes to these wonderful people:

Contributions of any kind welcome!