Tag: Code Generation

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

The full documentation for this is available on flutter.dev

When creating json_serializable classes the first time, you’ll get errors similar to what is shown in the image below.

IDE warning when the generated code for a model class does not exist yet.

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://flutter.dev/docs/development/data-and-backend/json#code-generation