Sub topic 15
Common pitfalls and version differences
This chapter assumes you have declared a freezed class, run build_runner and used copyWith. It collects the failures you are most likely to hit and explains how the freezed 2.x and 3.x syntax differ.
Missing or mismatched part files
Every freezed file depends on generated code. The part directive and the mixin name must match what the generator produces.
import 'package:freezed_annotation/freezed_annotation.dart';
part 'person.freezed.dart';
part 'person.g.dart';
@freezed
abstract class Person with _$Person {
const factory Person({required String name}) = _Person;
factory Person.fromJson(Map<String, dynamic> json) => _$PersonFromJson(json);
}Typical errors and their causes:
| Symptom | Likely cause |
|---|---|
| `Target of URI hasn't been generated: 'person.freezed.dart'` | `build_runner` has not run yet, or it failed. |
| `The name '_$Person' isn't a type` | The `part` line is missing or has the wrong file name. |
| `The method '_$PersonFromJson' isn't defined` | `part 'person.g.dart';` is missing, or `json_serializable` is not in `dev_dependencies`. |
| `Missing concrete implementation of ...` | The class does not use `with _$Person`, or the redirect target `_Person` is misspelled. |
The part file name is the source file name plus .freezed.dart. If you rename person.dart to user.dart, update the part lines and regenerate.
Stale generated code
Generated files do not update when you save the source file. They update only when build_runner runs again. If the editor shows errors that make no sense after you add a field, the generated file is probably out of date.
dart run build_runner build --delete-conflicting-outputsDuring active development, run the watcher so every save regenerates the output:
dart run build_runner watch --delete-conflicting-outputs--delete-conflicting-outputs removes generated files that conflict with the new build. Without it, a stale .g.dart file can stop the build with a "conflicting outputs" error.
Read the first error that build_runner prints. Later errors are often side effects of the first one. A syntax error in one model can prevent generation for the whole package.
Version differences: freezed 2.x and 3.x
Freezed 3.0 changed how classes are declared. Check the version in pubspec.yaml first, because many tutorials and Stack Overflow answers use the 2.x style.
| Topic | Freezed 2.x | Freezed 3.x |
|---|---|---|
| Data class declaration | `@freezed class Person with _$Person` | `@freezed abstract class Person with _$Person` |
| Union declaration | `@freezed class State with _$State` | `@freezed sealed class State with _$State` |
| Handling unions | `when`, `map`, `maybeWhen` and similar methods, or pattern matching | Dart 3 pattern matching. The `when` and `map` families are removed. |
| Custom members | Add `const Person._();` | Same |
If you upgrade from 2.x, expect two kinds of compile errors. A class that has a factory constructor but is not abstract fails to compile. Any call to .when(...) or .map(...) fails because the methods no longer exist. Rewrite them as switch expressions:
// Freezed 2.x style, no longer available in 3.x
// state.when(
// loading: () => 'Loading',
// data: (items) => '${items.length} items',
// error: (message) => 'Error: $message',
// );
// Freezed 3.x style
String describe(LoadState state) => switch (state) {
LoadStateLoading() => 'Loading',
LoadStateData(:final items) => '${items.length} items',
LoadStateError(:final message) => 'Error: $message',
};Pin compatible versions of freezed, freezed_annotation, json_serializable, json_annotation and build_runner. The generator and its annotation package should come from the same major release line. A mismatch produces confusing errors, such as an annotation that the generator does not recognize.
Pattern matching needs Dart 3. Set the SDK constraint in pubspec.yaml to at least ^3.0.0.
Forgetting the private constructor
A freezed class has only redirecting factory constructors. Dart has no generative constructor to attach members to, so a custom getter or method fails to compile unless you add a private constructor:
import 'package:freezed_annotation/freezed_annotation.dart';
part 'temperature.freezed.dart';
@freezed
abstract class Temperature with _$Temperature {
const Temperature._();
const factory Temperature({required double celsius}) = _Temperature;
double get fahrenheit => celsius * 9 / 5 + 32;
}If you add a method to a class without const Temperature._();, the compiler reports an error about the missing constructor. Add the constructor and regenerate.
Shallow immutability of collections
A freezed class is immutable at the field level. You cannot reassign person.name. That guarantee does not extend to everything a field refers to.
Freezed wraps List, Map and Set fields in unmodifiable views by default. Calling add on such a list throws an UnsupportedError. It is a runtime error, not a compile error:
import 'package:freezed_annotation/freezed_annotation.dart';
part 'cart.freezed.dart';
@freezed
abstract class Cart with _$Cart {
const factory Cart({required List<String> items}) = _Cart;
}
void main() {
final cart = Cart(items: ['apple']);
// Throws UnsupportedError at runtime:
// cart.items.add('pear');
// Correct: build a new list and a new Cart.
final updated = cart.copyWith(items: [...cart.items, 'pear']);
print(updated.items); // [apple, pear]
}Two limits remain:
- The wrapping applies to the collection itself. If the list holds mutable objects, such as a plain class with non-final fields, you can still change those objects. Make element types immutable too.
- Equality compares collection contents. Two carts with equal lists are equal, which is usually what you want. Equality is only reliable if the elements implement
==correctly.
You can turn off the unmodifiable wrapping in build.yaml with the make_collections_unmodifiable: false option. Doing so gives up the runtime protection, so it rarely pays off.
JSON pitfalls
Three problems come up repeatedly when you add fromJson and toJson.
Nested objects are not converted in toJson. By default json_serializable puts the nested instance into the output map instead of calling its toJson. jsonEncode then fails, or calls toJson implicitly, depending on the case. Fix it for the whole package in build.yaml:
targets:
$default:
builders:
json_serializable:
options:
explicit_to_json: trueField names must match. The JSON key e_mail does not map to a field named email unless you add @JsonKey(name: 'e_mail'). A missing required key throws at parse time. A missing key on a field with @Default uses the default.
Unions need a discriminator. A sealed union with fromJson reads a runtimeType key by default to choose the constructor. Your backend probably does not send it. Set a different key with @Freezed(unionKey: 'type') and use @FreezedUnionValue('...') to map values to constructors.
Equality and `copyWith` surprises
copyWithcannot set a nullable field tonullin some older freezed versions, becausenullmeant "keep the current value". Freezed handles this for nullable fields in current releases. If you see the old behavior, check your version before you work around it.toStringis generated, but it prints every field. Do not log models that contain secrets such as tokens.- Two instances of different freezed classes are never equal, even if their fields match. Equality checks the runtime type.
constconstructors give canonical instances.identical(const Person(name: 'A'), const Person(name: 'A'))is true. Do not useidenticalas a general equality test.
Generated files and version control
Teams split on whether to commit *.freezed.dart and *.g.dart.
- Committing them means a fresh clone compiles at once, and code review shows generated changes. The cost is noisy diffs and merge conflicts in generated files.
- Ignoring them keeps the repository small. The cost is that every developer and every CI job must run
build_runnerbefore analysis or tests.
Pick one policy and record it in the README. If you ignore the files, add a build_runner step to CI before flutter analyze and flutter test. If you commit them, add a CI check that regenerates and fails if git diff is not empty, so stale generated code cannot slip in.
Exercise
After upgrading to freezed 3.x, your project reports two errors. One is "The method 'when' isn't defined for the type 'LoadState'". The other is on a data class that has a factory constructor and is declared as @freezed class Person with _$Person. What changes fix both?
Show answer
Replace each when(...) call with a switch expression that uses Dart 3 patterns, such as LoadStateLoading() => ... and LoadStateData(:final items) => ..., because freezed 3 removed when and map. Declare the data class as @freezed abstract class Person with _$Person, and declare unions as sealed class. Then run dart run build_runner build --delete-conflicting-outputs to regenerate.
Exercise
A Cart model has final List<String> items. A teammate calls cart.items.add('pear') and the app crashes with an UnsupportedError. Why does this happen, and how do you add the item correctly?
Show answer
Freezed wraps collection fields in unmodifiable views, so mutating them throws at runtime. Create a new list and a new object instead: cart.copyWith(items: [...cart.items, 'pear']).