JSON

Flutter: generating *.g.dart files for json serialization

By

in

When working on mobile apps, you might need to communicate with a web server or easily store structured data. In such cases, JSON is a good solution to handle the data. But this also requires the serialization of data – turning a data structure into a string – or the other way round, deserialization – means turing a string into a data structure. Flutter provides a way to use automated serialization using code generation. This is described in detail on flutter.dev.

When creating json_serializable classes the first time, you might get some errors similar to what is shown in the image below:

error message in code editor

These errors are entirely normal and are simply because the generated code for the model class does not exist yet. To resolve this, run the code generator that generates the serialization boilerplate.

There are two ways of running the code generator.

One-time code generation

By running 

flutter pub run build_runner build

in the project root, you generate JSON serialization code for your models whenever they are needed. This triggers a one-time build that goes through the source files, picks the relevant ones, and generates the necessary serialization code for them.

While this is convenient, it would be nice if you did not have to run the build manually every time you make changes in your model classes.

Generating code continuously

watcher makes our source code generation process more convenient. It watches changes in our project files and automatically builds the necessary files when needed. Start the watcher by running

flutter pub run build_runner watch

in the project root.

It is safe to start the watcher once and leave it running in the background.

Source: https://docs.flutter.dev/data-and-backend/serialization/json#code-generation



Comments

Leave a Reply

Your email address will not be published. Required fields are marked *