JSON Serialization of Stores
The package is a popular way to encode/decode between json representations of your models. It works by attaching the
@jsonSerializable
annotation to the Store
classes. Since this is a custom annotation, we have to invoke the build_runner
command, just like we do for mobx_codegen
.
Let's add support for dart_json_mapper
to the todos example.
See the complete code here.
Adding dependency in pubspec.yaml
The first step is to include the dependency on the and
packages. We add this to the
pubspec.yaml
and run flutter packages get
to download it.
build.yaml
Configure main.dart
Configure Adding annotations
To make our store classes travel to JSON and back, we need to annotate them with @jsonSerializable
:
On with the code-generation
With these changes, let's run the build_runner
command in the project folder:
This will generate main.reflectable.dart
file, which you should add to your .gitignore
as *.reflectable.dart
.
It's recommended not to commit this generated code to your repository, since it's 100% generated and essential for compile time only.
JSON Serialization / Deserialization
Summary
With these changes, you should now be able to serialize the Todos to/from JSON
โ๏ธ. BTW, its worth noting that mobx_codegen
can co-exist with other generators.
See the complete code here.