The Best Way generates models in Flutter | freezed

Wing CHAN
2 min readMay 22, 2021

Goals: I need to convert the following product json to a model

I have always used quicktype to convert json directly to model, but it is very inconvenient when I need to change some properties of the model, I need to change them in different places repeatedly, and sometimes there are even cases of missing changes.

Below is the normal model, I have highlighted the areas of repetition, you can see that if you need to change it at least 3 times, in addition, if there are default values or emun needs, you also need to implement it yourself.

The following image shows the use of the freezed model, you can see that there is no duplication of definitions, in addition, it also supports default values and emun and other functions, more functions can see freezed and json_serializable.

Usage

Paste json on quicktype , select freezed

Note: quicktype can only generate basic properties, like JsonKey these need to be added by yourself.

Install the required dependencies into the flutter project’s pubspec.yaml

environment:
sdk: ">=2.7.0 <3.0.0"
dependencies:
freezed_annotation: ^0.12.0
dev_dependencies:
build_runner: ^1.11.5
freezed: 0.12.7
json_serializable: ^3.5.1

Based on the `part ‘product.freezed.dart’ and `part ‘product.g.dart’` in product.dart will generate `product.freezed.dart` and `product.g.dart` when it is run.

flutter pub run build_runner build --delete-conflicting-outputs

If you don’t want to see the generated files in android studio, you can set ignore it.

I hope you enjoy reading this article and hitting clap 👏 .

--

--