Migrating from 2.x to 3.x
Opened this issue · 2 comments
The following breaking changes need to be migrated when upgrading to version 3.x:
Mapper Container
- All
<ClassName>Mapper.container
s are removed
Instead use the global MapperContainer.globals
container.
T decode<T>(String json) {
- MyClassMapper.container.fromJson<T>(json);
+ MapperContainer.globals.fromJson<T>(json);
}
Initializing Mappers
Mappers can be used
- explicitly trough calling e.g.
MyClassMapper.fromJson(json)
, or - implicitly trough a generic parameter, e.g.
MapperContainer.globals.fromJson<MyClass>(json)
.
When used implicitly, mappers must be initialized beforehand by calling their MyClassMapper.ensureInitialized()
method.
void main() {
+ MyClassMapper.ensureInitialized();
+ MyOtherClassMapper.ensureInitialized();
...
}
Generated Initializer
Calling ensureInitialized()
for every mapper in your project can be cumbersome. Therefore you can generate an initializer functions that automatically initializes all mappers in scope.
To do this set the generateInitializerForScope
property on @MappableLib()
, which replaces the createCombinedContainer
property.
@MappableLib(
- createCombinedContainer: true, discoveryMode: DiscoveryMode.package,
+ generateInitializerForScope: InitializerScope.package,
)
library main;
- import 'main.container.dart';
+ import 'main.init.dart';
void main() {
- mainContainer.fromJson<...>(...);
+ initializeMappers();
+ MapperContainer.globals.fromJson<...>(...);
}
When creating a library which does not have a main method, such as one for communicating with an API, should initializeMappers()
be called when the class is constructed or somewhere else? What happens if it gets called more than once? What if the library is then used in a larger project which is also using dart_mappable?
Initializing mappers is idempotent, meaning executing it more than once has no effect and is safe to do.
You can basically call it whenever as long as its before the usage of a mapper.