schultek / dart_mappable

Improved json serialization and data classes with full support for generics, inheritance, customization and more.
https://pub.dev/packages/dart_mappable
MIT License
145 stars 21 forks source link

Migrating from 2.x to 3.x #71

Open schultek opened 1 year ago

schultek commented 1 year ago

The following breaking changes need to be migrated when upgrading to version 3.x:

Mapper Container

  1. All <ClassName>Mapper.containers 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

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<...>(...);
} 
point-source commented 1 year ago

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?

schultek commented 1 year ago

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.