iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🧊

[Flutter/Dart] Freezed 3.0 Released! Summary of Major Changes from 2.x

に公開

Recently (though it seems it was about two months ago), Freezed 3.0 was released. I have researched and summarized the major changes when updating from 2.x. [1]

Breaking Changes

Requiring sealed or abstract

Classes using factory constructors now require abstract (for single classes) or sealed (for union types).

@freezed
-class Person with _$Person {
+abstract class Person with _$Person {
  const factory Person({
    required String firstName,
    required String lastName,
    required int age,
  }) = _Person;

  factory Person.fromJson(Map<String, Object?> json)
      => _$PersonFromJson(json);
}
@freezed
-class Model with _$Model {
+sealed class Model with _$Model {
  factory Model.first(String a) = First;
  factory Model.second(int b, bool c) = Second;
}

Removal of map, when, and Their Derivative Methods

Methods such as map and when, which were deprecated following the introduction of pattern matching in Dart, have been removed.

Solution

Please rewrite your code to use Dart's pattern matching.

final model = Model.first('42');

-final res = model.map(
-  first: (String a) => 'first $a',
-  second: (int b, bool c) => 'second $b $c',
-);
+final res = switch (model) {
+  First(:final a) => 'first $a',
+  Second(:final b, :final c) => 'second $b $c',
+};

New Features

Mixed mode

A new definition method called mixed mode is now available.

In the traditional definition method using factory constructors, Freezed generated the constructors and properties.
In mixed mode, constructors and properties can be defined by the developer.

Conventional definition method (Factory constructor)

@freezed
sealed class Usual with _$Usual {
  // Freezed generates the constructor and properties
  factory Usual({int? a}) = _Usual;
}

Available from 3.0 (Regular constructor)

@freezed
class Usual with _$Usual {
  // Developer defines the constructor and final properties
  Usual({this.a});
  final int? a;
}

This has several advantages:

  • For simple data classes, you can define properties with a regular constructor without using factory (avoiding "Freezed-specific syntax").
  • Union types can still be defined using factory as before.

Also, with mixed mode making regular constructors available, it is now possible to call super constructors as follows:

class Base {
  Base(String value);
}

@freezed
class Usual extends Base with _$Usual {
  // Calling super with a regular constructor
  Usual({int? a}) : a = a ?? 0, super('value');
  final int a;
}

Inheritance and Non-Constant Default Values

In previous versions of Freezed, there were limitations on class inheritance (extends) and setting non-constant (non-const) default values for constructor arguments.
Freezed 3.0 enables these features by combining mixed mode with a private constructor (ClassName._()).

Previously, to define custom methods or properties in a Freezed class, you had to define an empty private constructor like ClassName._();. However, it was not possible to pass parameters to this ._() constructor.

@freezed
class Example with _$Example {
  Example._(); // Required for helloWorld() to work

  factory Example(String name) = _Example;

  void helloWorld() => print('Hello $name');
}

In Freezed 3.0, you can pass arbitrary parameters to this private constructor. Freezed passes values from other factory constructors based on the parameter names. This enables calling super or setting non-constant default values.

Example of inheritance (extends):

class Subclass {
  Subclass.name(this.value);
  final int value;
}

@freezed
class MyFreezedClass extends Subclass with _$MyFreezedClass {
  // Receive parameters in the private constructor ._
  // and call super.name() to pass values to the base class (Subclass) constructor
  MyFreezedClass._(super.value): super.name();

  // Freezed generates code to pass the value field to MyFreezedClass._
  factory MyFreezedClass(int value, /* other fields */) = _MyFreezedClass;
}

As shown below, non-constant default values can also be used.

@freezed
sealed class Response<T> with _$Response<T> {
  // Set a non-constant default value DateTime.now() for the time parameter within the private constructor ._
  Response._({DateTime? time}) : time = time ?? DateTime.now();

  // Each factory constructor can pass values to the private constructor ._() as needed
  // If time is not specified, the default value in ._() is used
  factory Response.data(T value, {DateTime? time}) = ResponseData;

  // If the parameters of the private constructor ._() are named and optional ({DateTime? time}),
  // the default value set in ._() will be used unless explicitly specified in the factory constructor.
  factory Response.error(Object error) = ResponseError;

  @override
  final DateTime time;
}

"Eject" Union Cases

It is now possible to use custom-defined classes for specific cases of union types, without having Freezed perform code generation for them.

@freezed
sealed class Result<T> with _$Result {
  Result._();

  // ResultData is undefined, so Freezed generates it as usual
  factory Result.data(T data) = ResultData;

  // By specifying an existing class name (ResultError) on the right side, Freezed
  // will not generate code for that case (ResultError) and will use the specified class directly
  factory Result.error(Object error) = ResultError;
}

// Custom-defined ResultError class
// It must extend the sealed class Result<T>
class ResultError<T> extends Result<T> {
  ResultError(this.error): super._();
  final Object error;
}

This custom-defined class (ResultError) can also be a Freezed class and can be combined with the aforementioned mixed mode.

// A simple class using mixed mode
@freezed
class ResultError<T> extends Result<T> with _$ResultError<T> {
  ResultError(this.error): super._();
  final Object error;
}

// Alternatively, it's also possible to use a factory
@freezed
abstract class ResultError<T> extends Result<T> with _$ResultError<T> {
  ResultError._(): super._();
  factory ResultError(Object error) = _ResultError;
}

Other Changes

Automatic Insertion of // dart format off

If formatting is disabled in the Freezed settings (format: false, which is the default), // dart format off is now added to the beginning of the generated .freezed.dart files.
This may eliminate the need to exclude generated files from CI format checks in some cases.

Making Union Cases Private

It is now possible to make factory constructors corresponding to each case of a union type private (_).

@freezed
sealed class Result<T> with _$Result {
  // This ._data() can now be written starting from 3.0
  factory Result._data(T data) = ResultData; 
  factory Result.error(Object error) = ResultError;
}

References

脚注
  1. This is largely a translation of the official CHANGELOG / Migration Guide. I have corrected some code that caused errors during file generation. ↩︎

GitHubで編集を提案

Discussion