Sub topic 7
Defaults, Optional Fields and Assertions
This chapter covers how a freezed class describes which fields are required, which can be left out, which have a fallback value, and which values are invalid. It assumes you can write Dart classes with named parameters, you understand null safety, and you have already set up freezed and run build_runner as shown in earlier chapters.
Three kinds of field
Every field in a freezed factory constructor falls into one of three groups. The group you choose decides what callers must write and what the compiler checks for you.
| Kind | Declaration | Caller must pass it? | Value when omitted |
|---|---|---|---|
| Required | `required String name` | Yes | Not applicable |
| Default | `@Default(0) int age` | No | The default value |
| Optional (nullable) | `String? nickname` | No | `null` |
These map directly onto Dart's own named-parameter rules. Freezed copies the parameter list into the generated class, so the same compile-time checks apply. If you forget a required field, the analyzer reports an error at the call site, not at run time.
The running example
The example below uses all three kinds in one class, plus an assertion.
import 'package:freezed_annotation/freezed_annotation.dart';
part 'person.freezed.dart';
@freezed
abstract class Person with _$Person {
@Assert('age >= 0')
const factory Person({
required String name,
@Default(0) int age,
String? nickname,
}) = _Person;
}
void main() {
const ada = Person(name: 'Ada', age: 36);
final older = ada.copyWith(age: 37);
print(ada == older); // false
print(older); // Person(name: Ada, age: 37, nickname: null)
}Run dart run build_runner build --delete-conflicting-outputs before running this, or person.freezed.dart will not exist and the file will not compile.
Required fields
A field marked required has no fallback. Use it when a value of the object makes no sense without that field, such as an identifier or a name.
const Person(); // compile error: the named parameter 'name' is requiredPrefer required over a nullable field when the data is always present. A nullable field forces every reader to handle null. A required field moves that burden to the one place that creates the object.
Default values with @Default
The @Default annotation supplies a value when the caller omits the field. The annotated parameter stays non-nullable, so person.age is always an int.
const baby = Person(name: 'Sam');
print(baby.age); // 0Two rules matter here:
- The argument to
@Defaultmust be a compile-time constant, because it is placed in an annotation. Numbers, strings, booleans,constcollections, andconstconstructor calls all work. A value computed at run time, such asDateTime.now(), does not. - Pass the Dart source of the value. For a list use
@Default([])or, to be explicit,@Default(<String>[]). For an enum use@Default(Role.guest).
enum Role { guest, member, admin }
@freezed
abstract class Account with _$Account {
const factory Account({
required String id,
@Default(Role.guest) Role role,
@Default(<String>[]) List<String> tags,
}) = _Account;
}Defaults are not copyWith resets
A default applies only when the constructor is called without that argument. It does not act as a "reset" value. Calling copyWith() with no arguments keeps the current values, and copyWith(age: null) is not a way to restore the default.
Defaults and JSON
When you add fromJson (covered in the JSON chapter), the default also applies when the key is missing from the incoming map. This is a common reason to use @Default: an API that omits a field then produces a valid object instead of a type error.
Optional fields with nullable types
A field typed String? is optional. If the caller omits it, it is null. Use this when "no value" is a meaningful state, for example a user who has no nickname.
Be careful to separate two cases that look alike:
- "No value" is a real state: use a nullable type.
- "A sensible value exists when nothing is given": use
@Default.
An empty string is rarely a good stand-in for "missing". It makes nickname == '' and nickname == null both possible, and callers must remember to check for both.
The copyWith limitation for nullable fields
With a nullable field you may want to change a value back to null. In current freezed versions the generated copyWith can distinguish "argument not passed" from "argument passed as null", so this works:
const named = Person(name: 'Ada', nickname: 'A');
final cleared = named.copyWith(nickname: null);
print(cleared.nickname); // nullFreezed achieves this with an internal sentinel value rather than a plain null default. This is a real difference from a hand-written copyWith such as nickname: nickname ?? this.nickname, which can never clear a field. If you write your own copyWith in a non-freezed class, you will hit that limitation.
Assertions with @Assert
@Assert attaches a Dart assert to the generated constructor. The argument is a string containing a boolean expression over the constructor parameters.
@Assert('age >= 0')
const factory Person({
required String name,
@Default(0) int age,
String? nickname,
}) = _Person;You can stack several assertions, and each can carry a message as a second argument:
@Assert('name.isNotEmpty', 'name must not be empty')
@Assert('age >= 0', 'age must not be negative')
const factory Person({
required String name,
@Default(0) int age,
}) = _Person;What assertions do and do not guarantee
Assertions are a development tool. Dart evaluates assert only in debug mode and in tests. In a release build (flutter build apk --release) they are removed, so an invalid object can be created without any error.
This has practical consequences:
- Use
@Assertto catch programmer mistakes, such as passing a negative age from your own code. - Do not rely on it to reject untrusted input such as JSON from a server or text typed by a user. Validate that input explicitly before building the object, and handle failure in a way that works in release builds.
- Because the expression is a string, the analyzer does not check it as Dart code. A typo, such as a misspelled parameter name, shows up when generated code fails to compile or when the constructor runs.
Also note that the assertion runs in the constructor, so copyWith goes through it too. Calling ada.copyWith(age: -1) throws an AssertionError in debug mode.
void main() {
const ada = Person(name: 'Ada', age: 36);
try {
ada.copyWith(age: -1);
} on AssertionError catch (e) {
print('Rejected: ${e.message}');
}
}The message is only available if you supplied one as the second @Assert argument.
When to use a constructor body instead
If a rule needs to run in release builds, or must produce a friendly error, assertions are the wrong tool. Two alternatives work with freezed:
- A factory function or a static method that validates and returns a result type (see the sealed union chapter for a way to model success and failure).
- A custom constructor with a body, which requires the private
const Person._();constructor described in the next chapter.
Keep the freezed constructor itself a plain description of data, and put policy elsewhere.
Choosing between the three tools
Common errors
- A
@Defaultvalue that is not constant. The analyzer reports that annotation arguments must be constants. Move the dynamic value to the call site, or make the field nullable. - Combining
requiredwith@Default. A default means the argument can be omitted, sorequiredcontradicts it. Use one or the other. - Using
@Defaulton a nullable field without thinking.@Default('x') String? nicknameis legal, but the field then can only benullif the caller passesnullexplicitly. Most of the time you want either a non-nullable type with a default, or a plain nullable type. - Forgetting to rerun the generator. Changing a default or an assertion string changes the generated code. If behavior does not match your source, rerun
dart run build_runner build --delete-conflicting-outputs. - Expecting assertions in production. See above. They are stripped from release builds.
Putting it together
A model for a profile form shows all the pieces working together. The displayName is required, the theme falls back to a constant, the bio can be absent, and an assertion guards a range.
import 'package:freezed_annotation/freezed_annotation.dart';
part 'profile.freezed.dart';
enum Theme { light, dark }
@freezed
abstract class Profile with _$Profile {
@Assert('displayName.isNotEmpty', 'displayName must not be empty')
@Assert('age == null || age >= 13', 'age must be at least 13')
const factory Profile({
required String displayName,
@Default(Theme.light) Theme theme,
String? bio,
int? age,
}) = _Profile;
}
void main() {
const p = Profile(displayName: 'Ada');
print(p.theme); // Theme.light
print(p.copyWith(bio: 'Mathematician'));
}Note the assertion age == null || age >= 13. Because age is nullable, the expression must handle null first, or the generated code will not compile under null safety.
Exercise
A Flutter app builds a Person from server JSON in release mode. The server sometimes sends "age": -5, and the class uses @Assert('age >= 0'). Will the app reject the value? What would you change?
Show answer
No. Assertions are removed from release builds, so the object is created with age -5. Validate the JSON explicitly before or after calling fromJson, for example in a function that checks the value and returns an error state, and keep @Assert only as a development-time check for your own code.
Exercise
You want a Settings class where pageSize is 20 unless specified, locale may be absent, and userId must always be given. Write the factory constructor parameters.
Show answer
required String userId, @Default(20) int pageSize, String? locale