Flutter Freezed — The complete crash course
Introduction
Freezed is a code-generation package that helps you create data classes in Dart. It prevents you from writing hundreds of error-prone lines. Sometimes you just want a class that accepts its values in a constructor, a toString method and maybe value equality. That alone is a lot. But now imagine you want objects to remain immutable. For that you need an extra copyWith method. If you know how to implement all this in Dart, you surely know that it takes a many lines of code to achieve this. And that’s where freezed comes in…
Installation
First, you need to add the freezed
package to your dev_dependencies and add freezed_annotation
as a dependency. To generate code, we still need the build_runner
package in the dev_dependencies. Also, we want to use the package jsonn_serializable
in dev_dependencies as well as json_annotation
in dependencies to handle json easier (toJson and fromJson).
Here are all the commands you need:
flutter pub add freezed_annotation
flutter pub add dev:build_runner
flutter pub add dev:freezed
flutter pub add json_annotation
flutter pub add dev:json_serializable
Usage
First you need to create a class with the@freezed
or @Freezed()
annotation.