http_services
一个基于 Dio 的 Dart 包,提供基础模型以处理 HTTP 服务请求。
一个用于处理 HTTP 服务的 Dart 包
^5.5.0+1^2.0.0^1.3.0^4.0.0^1.15.7^0.6.1以下为英文项目原文快照,最新内容请访问 GitHub。
A package to support the creation of Http services in a Dart application.
Every request should extend RequestBase and implement its overrides:
endpoint: Specify the path of the requesttoJson: This method is used for the request's serializationtoData: This is an optional override in case you need to post a non JSON body. It returns an object of type T.By default toData returns null
Every response should extend ResponseBase
All the exceptions of this package extend HttpServiceException
This is thrown when something is wrong with the request (e.g. missing internet, resource not found, etc).
networkError signals if there was an outage in connectionhttpCode is the received HTTP status codehttpMessage is the received HTTP status messageThis is thrown when expected HTTP code doesn't match the received one.
expected is the expected status codeactual is the received status codeThis is thrown when an error occurs while mapping the response.
This is thrown when a request is canceled.
Every service should extend this.
To make a request within you service, you can use one of the following:
getQuery: perform a GET requestpostData: perform a POST requestpostJson: perform a POST request with a JSON bodyputData: perform a PUT requestputJson: perform a PUT request with a JSON bodydeleteData: perform a DELETE requestdeleteJson: perform a DELETE request with a JSON bodypatchData: perform a PATCH requestpatchJson: perform a PATCH request with a JSON bodydownload: downloads a filegetBytes: gets bytes from an endpointimport 'package:dio/dio.dart';
import 'package:http_services/http_services.dart';
import 'todos_service.dart';
class TodosRequest extends RequestBase {
final int page;
TodosRequest(this.page) : assert(page != null && page > 0);
@override
String get endpoint => '/todos/$page';
@override
Map<String, dynamic> toJson() {
return {};
}
}
class TodosResponse extends ResponseBase {
final int userId;
final int id;
final String title;
final bool completed;
TodosResponse({
this.userId,
this.id,
this.title,
this.completed,
});
factory TodosResponse.fromJson(Map<String, dynamic> json) => TodosResponse(
userId: json['userId'],
id: json['id'],
title: json['title'],
completed: json['completed'],
);
}
class TodosService extends HttpServiceBase {
TodosService(Dio dioInstance) : super(dioInstance);
Future<TodosResponse> getTodo(int page) {
final request = TodosRequest(page);
return getQuery(
request: request,
mapper: (json, _) => TodosResponse.fromJson(json),
);
}
}
void main() async {
final dio = Dio(
BaseOptions(
baseUrl: 'https://jsonplaceholder.typicode.com/',
),
);
final service = TodosService(dio);
try {
print("Requesting data...");
final response1 = await service.getTodo(1);
print(
"user id: ${response1.userId}\n"
"id: ${response1.id}\n"
"title: ${response1.title}\n"
"completed: ${response1.completed}",
);
} on HttpServiceException catch (e) {
print('Service exception: ${e.runtimeType}');
}
}
There might be some cases where the JSON response is not like this:
{
"data": [{"name": "Bob"},{"name":"Alice"}],
}
This will not be treated as a JSON since it's not a Map<String,dynamic> but it's a List<Map<String,dynamic>>.
A solution might be to use the orElse parameter when performing the HTTP request. Remember that orElse is executed to map any response body that's not Map<String,dynamic>.
Similarly, if you ever find yourself in need of sending a JSON like the one above, a solution might be to override the onData method of RequestBase in your request object and then using the *data version of the request.
For example:
class User{
final String name;
User(this.name);
Map<String,dynamic> toJson() => {'name': name};
}
class UsersToSend extends RequestBase{
final List<User> users;
UsersToSend(this.users);
@override
Map<String,dynamic> toJson() => {};
@override
List<User> toData() => users;
}
and then use postData instead of using postJson in your service.