Closed MBulli closed 3 months ago
The documentation hints that the annotation is an alternative way to MapperContainer.globals.use(CustomMapper())
, and in fact, if the annotation is used, the model's ensureInitialized()
method adds the mapper to the global container.
-@MappableClass(includeCustomMappers: [])
+@MappableClass(includeCustomMappers: [_CustomDateTimeMapper()])
class CustomMapperModel with CustomMapperModelMappable {
final DateTime dateTime;
diff --git a/lib/model.mapper.dart b/lib/model.mapper.dart
class CustomMapperModelMapper extends ClassMapperBase<CustomMapperModel> {
static CustomMapperModelMapper ensureInitialized() {
if (_instance == null) {
MapperContainer.globals.use(_instance = CustomMapperModelMapper._());
- MapperContainer.globals.useAll([]);
+ MapperContainer.globals.useAll([_CustomDateTimeMapper()]);
}
return _instance!;
}
So the behavior is intentional and my expectation was wrong. Still, I find it kinda misleading that the annotation alters the global container, since one could argue that the scope of the annotation should only be the annotated class itself.
Is there a way to apply a CustomerMapper only to the class and not to others? Or do I have to use hooks on the fields?
rtfm ... Hooks are the way to go, just as the documentation says ;)
This gives you the possibility to use different custom mappers on the same type, especially on a field-by-field level.
I have the following code:
If you use it like this:
You get the following output:
Is this intended behavior? My expectation was that the
DateTime
values ofDefaultMapperModel
are always converted to ISO-8601 (following the config) and that onlyCustomMapperModel
uses my custom format mapper. But the call to toJson() on aCustomMapperModel
seems to alter some sort of global state.