Sub topic 13
Generic response wrappers
Most REST APIs wrap their payloads in the same envelope, such as {"data": ..., "message": ...} or a paginated list with a cursor. Writing one wrapper class per endpoint duplicates code. This chapter shows how to write one generic class, ApiResponse<T>, and have json_serializable generate its JSON code.
This chapter assumes you have annotated models working with build_runner, know how fromJson and toJson are generated, and are comfortable with Dart generics and function types. It reuses the User model from earlier chapters.
Why a plain generic class fails
Suppose the API returns this for a single user:
{"data": {"id": 1, "name": "Ada"}, "message": "ok"}The obvious wrapper is a class with a type parameter T for the data field. The problem is that json_serializable generates code at build time and cannot know which T you will use at runtime. Dart also erases nothing here (generics are reified), but the generator has no way to call T.fromJson, because static members and constructors cannot be reached through a type parameter.
Without extra help, the generator treats T like a value that JSON already decodes to. It casts the raw value as T when reading and writes it unchanged when serializing. This works for ApiResponse<String> or ApiResponse<int>. It fails at runtime for ApiResponse<User>, because the raw value is a Map<String, dynamic> and not a User.
The fix is to pass the conversion functions in as arguments. The genericArgumentFactories option does this.
Enabling genericArgumentFactories
Set genericArgumentFactories: true on the annotation. The generator then adds one function parameter per type parameter to the generated functions. Your hand-written fromJson and toJson must accept and forward those parameters.
import 'package:json_annotation/json_annotation.dart';
part 'api_response.g.dart';
@JsonSerializable(genericArgumentFactories: true)
class ApiResponse<T> {
const ApiResponse({required this.data, this.message});
factory ApiResponse.fromJson(
Map<String, dynamic> json,
T Function(Object? json) fromJsonT,
) =>
_$ApiResponseFromJson(json, fromJsonT);
final T data;
final String? message;
Map<String, dynamic> toJson(Object? Function(T value) toJsonT) =>
_$ApiResponseToJson(this, toJsonT);
}Run dart run build_runner build --delete-conflicting-outputs. The generated file contains roughly this:
ApiResponse<T> _$ApiResponseFromJson<T>(
Map<String, dynamic> json,
T Function(Object? json) fromJsonT,
) =>
ApiResponse<T>(
data: fromJsonT(json['data']),
message: json['message'] as String?,
);
Map<String, dynamic> _$ApiResponseToJson<T>(
ApiResponse<T> instance,
Object? Function(T value) toJsonT,
) =>
<String, dynamic>{
'data': toJsonT(instance.data),
'message': instance.message,
};The two function types matter:
fromJsonTtakesObject?, notMap<String, dynamic>. The generator cannot assume what shapeThas, so your closure must cast.toJsonTtakes aTand returnsObject?. For a model it returns the map fromtoJson(). For a primitive it returns the value itself.
Using the wrapper
Each call site supplies the conversion for its own T:
import 'dart:convert';
import 'api_response.dart';
import 'user.dart';
void main() {
const body = '{"data": {"id": 1, "name": "Ada"}, "message": "ok"}';
final json = jsonDecode(body) as Map<String, dynamic>;
final response = ApiResponse<User>.fromJson(
json,
(data) => User.fromJson(data as Map<String, dynamic>),
);
print(response.data.name); // Ada
print(response.message); // ok
}The closure is where the cast belongs. If the server sends a list in data, the cast to Map<String, dynamic> throws a TypeError. That is the correct outcome: the payload did not match the contract.
For a list payload, change T and the closure:
final users = ApiResponse<List<User>>.fromJson(
json,
(data) => (data as List<dynamic>)
.map((e) => User.fromJson(e as Map<String, dynamic>))
.toList(),
);Serializing back
toJson needs the opposite function. A common mistake is passing a closure that returns the object itself, which leaves a User inside the map and makes jsonEncode fail:
final map = response.toJson((user) => user.toJson());
final text = jsonEncode(map);For a list, map each element:
final map = users.toJson(
(list) => list.map((u) => u.toJson()).toList(),
);A reusable paginated wrapper
Generic fields can also appear inside collections. The generator handles List<T> by calling your function on each element. Here is a paginated envelope that uses snake case keys:
import 'package:json_annotation/json_annotation.dart';
part 'paged_list.g.dart';
@JsonSerializable(
genericArgumentFactories: true,
fieldRename: FieldRename.snake,
)
class PagedList<T> {
const PagedList({
required this.items,
required this.totalCount,
this.nextPage,
});
factory PagedList.fromJson(
Map<String, dynamic> json,
T Function(Object? json) fromJsonT,
) =>
_$PagedListFromJson(json, fromJsonT);
final List<T> items;
final int totalCount;
final int? nextPage;
Map<String, dynamic> toJson(Object? Function(T value) toJsonT) =>
_$PagedListToJson(this, toJsonT);
}The name PagedList avoids a clash with Flutter's own Page<T> class from the navigation library. Check names against package:flutter imports when you pick wrapper names.
You can nest wrappers. The outer closure builds the inner wrapper and forwards the element closure:
final response = ApiResponse<PagedList<User>>.fromJson(
json,
(data) => PagedList<User>.fromJson(
data as Map<String, dynamic>,
(item) => User.fromJson(item as Map<String, dynamic>),
),
);Nesting gets noisy quickly. If a combination appears in many places, give it a named function:
User _userFromJson(Object? json) =>
User.fromJson(json as Map<String, dynamic>);
PagedList<User> _userPageFromJson(Object? json) =>
PagedList<User>.fromJson(json as Map<String, dynamic>, _userFromJson);Then ApiResponse<PagedList<User>>.fromJson(json, _userPageFromJson) reads cleanly and each cast lives in one place.
Behavior to know about
| Situation | What happens |
|---|---|
| `genericArgumentFactories` is off and `T` is a model | The generated code casts `as T`. It throws at runtime. |
| Several type parameters, such as `Result<T, E>` | One function parameter per type parameter, in declaration order. |
| `T` is nullable, such as `ApiResponse<User?>` | `fromJsonT` receives `null`. Your closure must handle it. |
| Field named `data` is missing from the JSON | `fromJsonT` still runs and receives `null`. A cast in the closure then throws. |
| The class has no generic fields at all | The extra parameters are still required by the generated signature. |
Two points need care. First, the generator does not apply required checks to generic fields. A missing data key looks the same to your closure as a literal null. If data is required, make the closure strict, and use checked mode (covered in the error handling chapter) to get a readable error. Second, fromJsonT is only called for fields declared with the type parameter. Fields typed String or int use the normal generated casts.
Testing a generic wrapper
A round-trip test needs both closures. Keep them in test helpers so the test reads like production code:
import 'dart:convert';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('ApiResponse<User> survives a JSON round trip', () {
const original = ApiResponse<User>(
data: User(id: 1, name: 'Ada', email: '[email protected]'),
message: 'ok',
);
final text = jsonEncode(original.toJson((u) => u.toJson()));
final restored = ApiResponse<User>.fromJson(
jsonDecode(text) as Map<String, dynamic>,
(data) => User.fromJson(data as Map<String, dynamic>),
);
expect(restored.data.id, original.data.id);
expect(restored.data.name, original.data.name);
expect(restored.message, original.message);
});
}Add one more test where data has the wrong shape, and expect a TypeError. This documents the failure mode and protects your closures.
Common errors
type '_Map<String, dynamic>' is not a subtype of type 'User'. The optiongenericArgumentFactoriesis missing, so the generator cast instead of calling your function.The argument type ... can't be assigned to the parameter type 'T Function(Object?)'. The closure declares its parameter asMap<String, dynamic>. Declare it asObject?and cast inside.Converting object to an encodable object failed.toJsonTreturned a model instead of a map.- The generated function has no extra parameters. The build output is stale. Rerun the build with
--delete-conflicting-outputs.
Exercise
An endpoint returns {"result": {"items": [{"id": 1, "name": "Ada"}], "total_count": 1}}. Using PagedList<T> from this chapter and a wrapper class named Envelope<T> with a field result of type T, write the closure passed to Envelope<PagedList<User>>.fromJson. What does the closure's parameter type have to be, and why?
Show answer
The parameter type must be Object?, because the generated fromJsonT signature is T Function(Object? json) and the generator cannot know the shape of T. The closure is (result) => PagedList<User>.fromJson(result as Map<String, dynamic>, (item) => User.fromJson(item as Map<String, dynamic>)). Each closure casts its own Object? input before use.
Exercise
You call ApiResponse<User>.toJson((u) => u) and then jsonEncode the result. Why is this a bug even if it sometimes seems to work, and what is the fix?
Show answer
The map still contains a User object instead of a plain Map. jsonEncode may fall back to calling toJson() on it, but that hides the mistake and breaks in tests that compare the map or when encoding with a custom toEncodable. The fix is to return the plain map: (u) => u.toJson().