照着 retrofit 撸了一个 Dart & Flutter http 库,欢迎 PR,flutter 项目地址:https://github.com/trevorwang/retrofit.dart
Retrofit For Dart
retrofit.dart is a type conversion dio client generator using source_gen and inspired by Chopper and Retrofit.
Usage
Generator
Add the generator to your dev dependencies
dependencies:
retrofit: any
logger: any #for logging purpose
dev_dependencies:
retrofit_generator: any
build_runner: any
Define and Generate your API
import 'package:json_annotation/json_annotation.dart';
import 'package:retrofit/retrofit.dart';
import 'package:dio/dio.dart';
part ‘example.g.dart’;
@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 {
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);
}
then run the generator
# dart
pub run build_runner build
flutter
flutter pub run build_runner build
Use it
import 'package:logger/logger.dart';
import 'package:retrofit_example/example.dart';
import 'package:dio/dio.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));
More
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 the recommanded to be used as the serialization tool.
...
[@GET](/user/GET)("/tasks")
Future<List<Task>> getTasks();
}
@JsonSerializable()
class Task {
String name;
Task({this.name});
factory Task.fromJson(Map<String, dynamic> json) => _$TaskFromJson(json);
}
HTTP Methods
The HTTP methods in the below sample are supported.
[@GET](/user/GET)("/tasks/{id}")
Future<Task> getTask([@Path](/user/Path)("id") String id);
@PATCH("/tasks/{id}")
Future<Task> updateTaskPart(
@Path() String id, @Body() Map<String, dynamic> map);
@PUT("/tasks/{id}")
Future<Task> updateTask(@Path() String id, @Body() Task task);
@DELETE("/tasks/{id}")
Future<void> deleteTask(@Path() String id);
@POST("/tasks")
Future<Task> createTask(@Body() Task task);
@POST(“http://httpbin.org/post”)
Future<void> createNewTaskFromFile(@Part() File file);
@POST(“http://httpbin.org/post”)
@FormUrlEncoded()
Future<String> postUrlEncodedFormData(@Field() String hello);
Get orignal HTTP reponse
[@GET](/user/GET)("/tasks/{id}")
Future<HttpResponse<Task>> getTask([@Path](/user/Path)("id") String id)
@GET("/tasks")
Future<HttpResponse<List<Task>>>> getTasks()
HTTP Header
-
Add a HTTP header from the parameter of the method
[@GET](/user/GET)("/tasks") Future<Task> getTasks([@Header](/user/Header)("Content-Type") String contentType );
-
Add staitc HTTP headers
[@GET](/user/GET)("/tasks") [@Headers](/user/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){
logger.i(it);
}).catchError((Object 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}");
break;
default:
}
});
}
照着 retrofit 撸了一个 Dart & Flutter http 库,欢迎 PR,flutter 项目地址:https://github.com/trevorwang/retrofit.dart
更多关于照着 retrofit 撸了一个 Dart & Flutter http 库,欢迎 PR,flutter 项目地址:https://github.com/trevorwang/retrofit.dart的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
楼主我给你提了好几个 bug,哈哈哈,修的都很快!
更多关于照着 retrofit 撸了一个 Dart & Flutter http 库,欢迎 PR,flutter 项目地址:https://github.com/trevorwang/retrofit.dart的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
您好 Trevor,
非常高兴地看到您基于 Retrofit 的思想,为 Dart 和 Flutter 社区创建了一个新的 HTTP 库!Retrofit 在 Java 和 Android 开发中一直是一个备受欢迎的网络请求库,其简洁的注解和强大的功能深受开发者喜爱。将这一理念带到 Dart 和 Flutter,无疑会极大地提升这两个平台上网络请求的开发效率。
您的项目 retrofit.dart
无疑是一个非常有价值的贡献。从项目地址来看,您已经很好地组织了代码,并且提供了基本的使用示例,这对于新上手的开发者来说非常友好。
关于 PR(Pull Request),我建议您在以下几个方面进一步完善项目,以吸引更多的关注和贡献:
- 文档:增加更详细的文档,包括 API 的使用方法、常见问题的解决方案等。
- 示例:提供更多的使用示例,特别是针对一些复杂场景的处理。
- 测试:增加单元测试和集成测试,确保库的稳定性和可靠性。
- 兼容性:确保库与不同版本的 Dart 和 Flutter 兼容。
此外,您也可以在 Flutter 社区、Dart 论坛以及相关的技术社交媒体上宣传您的项目,吸引更多的开发者参与和使用。
祝您的项目越来越完善,期待您为 Dart 和 Flutter 社区带来更多优质的开源项目!