0.4.1

Adapters

Flutter Data is extremely composable and customizable. This is accomplished through adapters (Dart mixins deriving from Repository<T>).

Adapters are Flutter Data’s building blocks.

In addition to the Repository public API, adapters can override:

Here is the protected API of an important core adapter, RemoteAdapter:

// @protected API  

String get baseUrl => 'http://127.0.0.1:8080/';

String urlForFindAll(params) => '$type';
DataRequestMethod methodForFindAll(params) => DataRequestMethod.GET;

String urlForFindOne(id, params) => '$type/$id';
DataRequestMethod methodForFindOne(id, params) => DataRequestMethod.GET;

String urlForSave(id, params) => id != null ? '$type/$id' : type;
DataRequestMethod methodForSave(id, params) => id != null ? DataRequestMethod.PATCH : DataRequestMethod.POST;

String urlForDelete(id, params) => '$type/$id';
DataRequestMethod methodForDelete(id, params) => DataRequestMethod.DELETE;

Map<String, dynamic> get params => {};
Map<String, dynamic> get headers => {};

Map<String, String> parseQueryParameters(Map<String, dynamic> params);

Future<R> withHttpClient<R>(OnRequest<R> onRequest);

FutureOr<R> withResponse<R>(http.Response response, OnResponseSuccess<R> onSuccess);

// serialization

Map<String, dynamic> serialize(T model);

Iterable<Map<String, dynamic>> serializeCollection(Iterable<T> models);

T deserialize(dynamic object, {String key, bool initialize = true});

Iterable<T> deserializeCollection(object);

A simple example would be:

mixin JSONPlaceholderAdapter<T extends DataSupport<T>> on RemoteAdapter<T> {
  @override
  String get baseUrl => 'https://my-json-server.typicode.com/flutterdata/demo/';
}

We simply add adapters as parameters to @DataRepository(). (No need to pollute our models with a thousand annotations!)

@DataRepository([StandardJSONAdapter, JSONPlaceholderAdapter]);

The generic repository is being overriden by StandardJSONAdapter first, and then JSONPlaceholderAdapter. Order matters!

Important: As the repository is generated, any change in the list of adapters must be followed by a build in order to take effect.

flutter packages pub run build_runner build

Trouble generating code? See here.

There are three bundled adapters in Flutter Data that demonstrate how powerful this concept is:

Of course, (1) these can be combined, and (2) there will be many more.

Adapters for Wordpress or Github REST access, or even a JWT authentication adapter are easy to build.

These examples and more can be found in the cookbook.