Smartstruct - Dart bean mappings - the easy nullsafe way!
Code generator for generating type-safe mappers in dart, inspired by https://mapstruct.org/
Overview
- Add smartstruct as a dependency, and smartstruct_generator as a dev_dependency
- Create a Mapper class
- Annotate the class with @mapper
- Run the build_runner
- Use the generated Mapper!
Installation
Add smartstruct as a dependency, and the generator as a dev_dependency.
https://pub.dev/packages/smartstruct
Run the generator
Usage
Create your beans.
To generate a mapper for these two beans, you need to create a mapper interface.
Once you ran the generator, next to your dog.mapper.dart a dog.mapper.g.dart will be generated.
dart run build_runner build
The Mapper supports positional arguments, named arguments and property access via implicit and explicit setters.
Case sensitivity
By default mapper generator works in case insensitivity manner.
As you can see, classes above got different field's names (case) for username. Because mappers are case insensitive by default, those classes are correctly mapped.
To create case sensitive mapper, you can add param caseSensitiveFields to @Mapper annotation. Case sensitive mapper is checking field's names in case sensitive manner.
Explicit Field Mapping
If some fields do not match each other, you can add a Mapping Annotation on the method level, to change the behaviour of certain mappings.
In this case, the field dogName of DogModel will be mapped to the field name of the resulting Dog
Function Mapping
The source attribute can also be a Function. This Function will then be called with the Source Parameter of the mapper method as a parameter.
Will generate the following Mapper.
Nested Bean Mapping
Nested beans can be mapped, by defining an additional mapper method for the nested bean.
Will generate the mapper
List Support
Lists will be mapped as new instances of a list, with help of the map method.
Will generate the Mapper
Injectable
The Mapper can be made a lazy injectable singleton, by setting the argument useInjection to true, in the Mapper Interface.
In this case you also need to add the injectable dependency, as described here. https://pub.dev/packages/injectable
Make sure, that in the Mapper File, you import the injectable dependency, before running the build_runner!
Examples
Please refer to the example package, for a list of examples and how to use the Mapper Annotation.
You can always run the examples by navigating to the examples package and executing the generator.
Roadmap
Feel free to open a Pull Request, if you'd like to contribute.
Or just open an issue, and i do my level best to deliver.