Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Migrating from 2.x to 3.x #71

Open
schultek opened this issue Feb 25, 2023 · 2 comments
Open

Migrating from 2.x to 3.x #71

schultek opened this issue Feb 25, 2023 · 2 comments

Comments

@schultek
Copy link
Owner

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

  • 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<...>(...);
} 
@point-source
Copy link
Contributor

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
Copy link
Owner Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants