Getting started¶
This page takes you from nothing to a working request in a few minutes.
Install¶
or add it to pubspec.yaml:
Then import it. The package re-exports dio, so you don't need a separate import for Dio, Options or CancelToken:
Requirements
Dart 3.12 or newer and Flutter 3.44 or newer.
Create the client¶
Create one PlayxNetworkClient for your app (or one per backend) and reuse it.
final client = PlayxNetworkClient(
dio: Dio(
BaseOptions(
baseUrl: 'https://api.thecatapi.com/v1/',
connectTimeout: const Duration(seconds: 20),
sendTimeout: const Duration(seconds: 20),
),
),
// Attached to every request, for example an auth token.
customHeaders: () async => {'authorization': 'Bearer $token'},
);
No Dio of your own?
PlayxNetworkClient.createDefaultDioClient(baseUrl: ...) builds a Dio with sensible defaults. It accepts every status code and lets the library decide what is an error.
Describe your data¶
A model only needs a way to build itself from decoded JSON:
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;
}
Make a request¶
getList returns a list of models. Use get for a single model.
final result = await client.getList<Cat>(
'images/search',
query: {'limit': 10},
fromJson: Cat.fromJson,
);
Handle the result¶
There is nothing to catch. The result is either a success or an error:
result.when(
success: (cats) {
print('Got ${cats.length} cats');
},
error: (error) {
print('Failed: ${error.message}');
},
);
Or use the getters:
That's it. Everything that can go wrong (no connection, a timeout, a 404, a server that returns invalid JSON, a mapper that throws) comes back as result.error with a typed exception.
What's next¶
- Making requests: all HTTP methods, path parameters,
dataKey, downloads. - Handling results:
when,mapand pattern matching. - Error handling: the exception types and custom error objects.
- Configuration: every client option and setting.