retrofit.dart retrofit 的dart 版本实现,利用了代码生成技术,不像java 使用的是动态代理,以下是一个参考试用
项目集成
- 依赖配置
name: cli
description: A sample command-line application.
version: 1.0.0
# repository: https://github.com/my_org/my_repo
environment:
sdk: ^3.1.3
# Add regular dependencies here.
dependencies:
retrofit: '>=4.0.0 <5.0.0'
logger: any #for logging purpose
json_annotation: ^4.8.1
dio: ^5.3.3
dev_dependencies:
lints: ^2.0.0
test: ^1.21.0
retrofit_generator: '>=7.0.0 <8.0.0'
build_runner: '>=2.3.0 <4.0.0'
json_serializable: ^6.6.2
- 定义接口访问签名
api_client.dart
import 'package:dio/dio.dart';
import 'package:json_annotation/json_annotation.dart';
import 'package:retrofit/retrofit.dart';
/// 生成的帮助方法
part 'api_client.g.dart';
/// 与retrofit 一致的接口访问定义
@RestApi(baseUrl: 'https://5d42a6e2bc64f90014a56ca0.mockapi.io/api/v1/')
abstract class RestClient {
factory RestClient(Dio dio, {String baseUrl}) = _RestClient;
@GET('/tasks')
Future<List<Task>> getTasks();
}
/// 实体定义
@JsonSerializable()
class Task {
const Task({this.id, this.name, this.avatar, this.createdAt});
/// json 处理
factory Task.fromJson(Map<String, dynamic> json) => _$TaskFromJson(json);
final String? id;
final String? name;
final String? avatar;
final String? createdAt;
/// json 处理
Map<String, dynamic> toJson() => _$TaskToJson(this);
}
- 代码生成
dart run build_runner build
- 集成调用
import 'package:cli/api_client.dart';
import 'package:dio/dio.dart';
void main() async {
final dio = Dio(); // Provide a dio instance
dio.options.headers['Demo-Header'] =
'demo header'; // config your dio headers globally
final client = RestClient(dio);
var result = await client.getTasks();
for (var element in result) {
print(
'id: ${element.id}, name: ${element.name}, avatar: ${element.avatar}');
}
}
- 运行效果
说明
etrofit.dart 实际上也是对于一些包的包装,同时利用了代码生成技术,实现了比较方便的dart rest api 调用
参考资料
https://github.com/trevorwang/retrofit.dart
https://github.com/dart-lang/source_gen
https://github.com/cfug/dio