playx_network 2.0.0
playx_network: ^2.0.0 copied to clipboard
playx_network is a Wrapper around Dio that can perform api request with better error handling and easily get the result of any api request.
Playx Network #
A Dio wrapper that turns every request into a typed result, gives errors names you can act on, and removes the try/catch.
Read the documentation · API reference · Changelog
Features #
- A result, never an exception. Every request returns a
NetworkResult: success with your model, or an error with a typed exception. - Errors you can act on. Offline, server unreachable, CORS, bad certificate, timeouts,
404,422... each has its own exception and message, ready to show to users. - Your models and your errors.
fromJsonfor the data,errorMapperfor the message anderrorExtraMapperfor your own error object. - Parsing off the UI thread. Map large responses in an isolate, and cancel the work with the request.
- Streaming and SSE. Consume Server-Sent Events, NDJSON and chunked responses as typed streams.
- Smart cancellation. Cancel by token or by tag, or let a new request replace the old one.
- Conveniences. Path parameters,
dataKeyextraction, custom headers and query, per-request settings, downloads. - Pretty logs. Request, response and error logging through Talker, with hidden headers and filters.
- Works with any
Dio. Bring your own instance, interceptors and adapter. Easy to test with a fake adapter.
Install #
flutter pub add playx_network
Requires Dart 3.12 and Flutter 3.44 or newer.
Quick start #
Create one client and reuse it:
import 'package:playx_network/playx_network.dart';
final client = PlayxNetworkClient(
dio: Dio(BaseOptions(baseUrl: 'https://api.thecatapi.com/v1/')),
// Attached to every request, for example an auth token.
customHeaders: () async => {'authorization': 'Bearer $token'},
);
Describe your data with a fromJson, make a request, and handle the result:
class Cat {
Cat({this.id, this.url});
factory Cat.fromJson(dynamic json) =>
Cat(id: json['id'] as String?, url: json['url'] as String?);
final String? id;
final String? url;
}
final result = await client.getList<Cat>(
'images/search',
query: {'limit': 10},
fromJson: Cat.fromJson,
);
result.when(
success: (cats) => print('Got ${cats.length} cats'),
error: (error) => print('Failed: ${error.message}'),
);
Or pattern match, and tell failures apart:
switch (result) {
case NetworkSuccess(:final data):
showCats(data);
case NetworkError(:final error):
final text = switch (error) {
NoInternetConnectionException() => 'You are offline',
ServerUnreachableException() => 'The server is not responding',
UnauthorizedRequestException() => 'Please sign in again',
ApiException(:final message) => message,
_ => 'Something went wrong',
};
showMessage(text);
}
Requests #
| Method | Sends | Returns |
|---|---|---|
get<T> / getList<T> |
GET |
NetworkResult<T> / NetworkResult<List<T>> |
post<T> / postList<T> |
POST |
NetworkResult<T> / NetworkResult<List<T>> |
put<T> / putList<T> |
PUT |
NetworkResult<T> / NetworkResult<List<T>> |
patch<T> / patchList<T> |
PATCH |
NetworkResult<T> / NetworkResult<List<T>> |
delete<T> / deleteList<T> |
DELETE |
NetworkResult<T> / NetworkResult<List<T>> |
download |
GET |
NetworkResult<Response> |
getStream<T> / postStream<T> |
GET / POST |
NetworkStreamResult<T> |
getSse / postSse |
GET / POST |
NetworkStreamResult<PlayxSseEvent> |
A few things that make requests shorter:
// Path parameters, URL-encoded for you.
await client.get<Post>('users/{userId}/posts/{postId}',
pathParameters: {'userId': 42, 'postId': 7}, fromJson: Post.fromJson);
// Read nested data out of an envelope.
await client.get<User>('me', dataKey: 'payload.user', fromJson: User.fromJson);
// Cancel the previous search when the user keeps typing.
await client.getList<Product>('search',
query: {'q': query}, cancelTag: 'search', fromJson: Product.fromJson);
// A DELETE with no body needs no mapper.
await client.delete<void>('posts/{id}', pathParameters: {'id': 7});
Documentation #
The documentation site covers everything in depth:
| Getting started | Install, create the client, make a request. |
| Making requests | All methods, path parameters, dataKey, downloads, per-request overrides. |
| Handling results | when, map, pattern matching, isolate mapping. |
| Error handling | Every exception, custom error objects, empty responses, 204. |
| Connection failures | Offline vs server down vs CORS vs TLS. |
| Streaming and SSE | Server-Sent Events, NDJSON, lifecycle. |
| Cancellation | Tokens, tags and search-as-you-type. |
| Logging | Settings, filters and hidden headers. |
| Testing | A fake adapter for fast, offline tests. |
| Configuration | Every client parameter and setting. |
Example #
A runnable app lives in example/. It performs requests against public APIs and shows the results and errors.
Contributing #
Issues and pull requests are welcome at github.com/playx-flutter/playx_network. Before sending a change, run:
dart format .
flutter analyze lib test
flutter test --coverage
The documentation lives in docs/ and is built with MkDocs Material: pip install -r docs/requirements.txt && mkdocs serve.
See also #
- Playx: the Playx ecosystem, less code and more productivity.
- playx_core: the shared classes and utilities this package builds on.
- playx_theme: multi-theme support for Flutter apps.
License #
MIT, see LICENSE.