listParser<T> function

List<T> Function(dynamic data) listParser<T>(
  1. T fromJson(
    1. Map<String, dynamic> json
    ), {
  2. String? key,
})

Turns a single-object parser into one that reads a JSON array, for the common list endpoint.

// [{"id": 1}, {"id": 2}]
final users = await api.getAs<List<User>>(
  endpoint: '/users',
  parser: listParser(User.fromJson),
);

// {"data": [{"id": 1}], "meta": {...}} — pull the array out of a wrapper
final users = await api.getAs<List<User>>(
  endpoint: '/users',
  parser: listParser(User.fromJson, key: 'data'),
);

Throws if the body is not a list (or key is missing), which the *As<T> methods turn into a Failure with ErrorSource.parseError rather than letting it escape.

Implementation

List<T> Function(dynamic data) listParser<T>(
  T Function(Map<String, dynamic> json) fromJson, {
  String? key,
}) {
  return (dynamic data) {
    final raw = key == null ? data : (data as Map)[key];
    return (raw as List)
        .map((item) => fromJson(Map<String, dynamic>.from(item as Map)))
        .toList();
  };
}