The most codeless way to write Rest API in Flutter (Retrofit + Freezed)
What you get from here? Reduced code and autocomplete from model
First, i have an API https://yourawesomeurl.com/user that returns the following result, so lets make it useable in flutter;
{
"status": 200,
"message": "fetch successfully!",
"data": {
"name": "Sheldon",
"age": 12
}
}
Setting Up
dependencies:
freezed_annotation: ^0.14.1
retrofit: ^1.3.4+1
json_annotation: ^4.0.0
dio: ^4.0.0-beta7
equatable: ^2.0.0
dev_dependencies:
build_runner: ^1.11.5
freezed: ^0.14.1
json_serializable: ^4.0.2
retrofit_generator: ^1.4.1+3
Template
base_response.dart
import 'package:equatable/equatable.dart';
import 'package:json_annotation/json_annotation.dart';
part 'base_response.g.dart';
@JsonSerializable(genericArgumentFactories: true)
class BaseResponse<T> extends Equatable {
final String status;
final T data;
final String message;
const BaseResponse({
this.status,
this.data,
this.message,
});
factory BaseResponse.fromJson(
Map<String, dynamic> json,
T Function(Object json) fromJsonT,
) {
return _$BaseResponseFromJson<T>(json, fromJsonT);
}
Map<String, dynamic> toJson(
Map<String, dynamic> Function(T value) toJsonT,
) {
return _$BaseResponseToJson<T>(this, toJsonT);
}
@override
List<Object> get props => [
status,
data,
message,
];
}
user_model.dart
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:json_annotation/json_annotation.dart';
import 'package:flutter/foundation.dart';
part 'user_model.freezed.dart';
part 'user_model.g.dart';
@freezed
class UserModel with _$UserModel {
const factory UserModel({required String name, required int age}) =
_UserModel;
factory UserModel.fromJson(Object? json) =>
_$UserModelFromJson(json as Map<String, dynamic>);
}
api.dart
import 'package:dio/dio.dart';
import 'package:yourawesomeproject/models/user_model.dart';
import 'package:retrofit/retrofit.dart';
import 'api_response.dart';
part 'api.g.dart';
@RestApi(baseUrl: "https://yourawesomeurl.com")
abstract class RestClient {
factory RestClient(Dio dio, {String baseUrl}) = _RestClient;
@GET("/user")
Future<ApiResponse<UserModel>> getUser();
}
Usage
Run this command to generate all the codes
> flutter pub run build_runner build
void main() async {
final dio = Dio();
// Optional: Due to self sign cert issue
(dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate =
(HttpClient client) {
client.badCertificateCallback =
(X509Certificate cert, String host, int port) => true;
return client;
};
final client = RestClient(dio);
client.getUser().then((it) => print(it.data!.name));
runApp(MyApp());
}
That's it, it will print out Sheldon