Introduction to freezed

Code generation for immutable classes that has a simple syntax/API without compromising on the features.

While there are many code-generators available to help you deal with immutable objects, they usually come with a trade-off. Either they have a simple syntax but lack features, or they have very advanced features but with complex syntax.

Installing and Using Freezed package

Add this to your package's pubspec.yaml file:

# pubspec.yaml
dependencies:
  freezed_annotation:

dev_dependencies:
  build_runner:
  freezed:

You can then install packages from the command line:

$ dart pub get

Alternatively, your editor might support dart pub get. Check the docs for your editor to learn more.

Example

Now you can use it in your Dart code by importing it like this:

import 'package:freezed_annotation/freezed_annotation.dart';

part 'my_demo.freezed.dart';

Note that the line partmy_demo.freezed.dartwill give you a warning, because the file is not created yet

Write the following code

import 'package:freezed_annotation/freezed_annotation.dart';

part 'my_demo.freezed.dart';

@freezed
class Person with _$Person {
  factory Person({ String name, int age }) = _Person;
}

To generate the code type the following command

$ flutter pub run build_runner build

Ignore lint warnings on generated files

It is likely that the code generated by Freezed will cause your linter to report warnings.

The solution to this problem is to tell the linter to ignore generated files, by modifying your analysis_options.yaml:

analyzer:
  exclude:
    - "**/*.freezed.dart"

Last updated