### Freezed File Setup Source: https://github.com/rrousselgit/freezed/blob/master/packages/freezed/README.md Basic setup for a Dart file using Freezed, including necessary imports and the 'part' directive. ```dart import 'package:freezed_annotation/freezed_annotation.dart'; part 'my_file.freezed.dart'; ``` -------------------------------- ### Run Build Runner for One-Time Build Source: https://github.com/rrousselgit/freezed/blob/master/_autodocs/project-setup.md Generate all code once. This is useful for initial setup or after significant changes. ```bash dart run build_runner build # or for Flutter flutter pub run build_runner build ``` -------------------------------- ### JSON Examples for Multiple Constructors Source: https://github.com/rrousselgit/freezed/blob/master/packages/freezed/README.md Illustrates how JSON objects with different 'runtimeType' values map to the respective constructors of the Freezed class. ```json [ { "runtimeType": "default", "a": "This JSON object will use constructor MyResponse()" }, { "runtimeType": "special", "a": "This JSON object will use constructor MyResponse.special()", "b": 42 }, { "runtimeType": "error", "message": "This JSON object will use constructor MyResponse.error()" } ] ``` -------------------------------- ### Install Freezed for Flutter Source: https://github.com/rrousselgit/freezed/blob/master/packages/freezed/README.md Installs the necessary packages for Freezed in a Flutter project, including build_runner and json_serializable if needed. ```console flutter pub add \ dev:build_runner \ freezed_annotation \ dev:freezed # if using freezed to generate fromJson/toJson, also add: flutter pub add json_annotation dev:json_serializable ``` -------------------------------- ### Install Freezed for Dart Source: https://github.com/rrousselgit/freezed/blob/master/packages/freezed/README.md Installs the necessary packages for Freezed in a Dart project, including build_runner and json_serializable if needed. ```console dart pub add \ dev:build_runner \ freezed_annotation \ dev:freezed # if using freezed to generate fromJson/toJson, also add: dart pub add json_annotation dev:json_serializable ``` -------------------------------- ### Minimal build.yaml Configuration for Freezed Source: https://github.com/rrousselgit/freezed/blob/master/_autodocs/project-setup.md A minimal build.yaml file to enable the Freezed builder. This is the simplest configuration to get Freezed working. ```yaml targets: $default: builders: freezed: enabled: true ``` -------------------------------- ### Model with When Method Example Source: https://github.com/rrousselgit/freezed/blob/master/packages/freezed/README.md Shows the 'when' method for pattern matching on a sealed class with constructors that have parameters. ```dart model.when( first: (String a) => 'first $a', second: (int b, bool c) => 'second $b $c' ) ``` -------------------------------- ### Union with When Method Example Source: https://github.com/rrousselgit/freezed/blob/master/packages/freezed/README.md Demonstrates the 'when' method for pattern matching on a sealed union with different constructors. ```dart union.when( (int value) => 'Data $value', loading: () => 'loading', error: (String? message) => 'Error: $message', ) ``` -------------------------------- ### Dart User fromJson Example Source: https://github.com/rrousselgit/freezed/blob/master/_autodocs/generated-methods.md Demonstrates how to create a User object from a JSON map using the generated fromJson factory. ```dart @freezed class User with _$User { const factory User(String name, int age) = _User; factory User.fromJson(Map json) => _$UserFromJson(json); } void main() { var json = {'name': 'Alice', 'age': 30}; var user = User.fromJson(json); print(user); // _User(name: Alice, age: 30) } ``` -------------------------------- ### Freezed Builder Configuration Source: https://github.com/rrousselgit/freezed/blob/master/_autodocs/README.md Configure the Freezed builder options in your build.yaml file. This example shows how to enable copyWith, equality checks, and toString overrides. ```yaml targets: $default: builders: freezed: options: format: false copy_with: true equal: true to_string_override: true union_key: runtimeType union_value_case: null make_collections_unmodifiable: true add_implicit_final: true ``` -------------------------------- ### Install Freezed and Build Runner Source: https://github.com/rrousselgit/freezed/blob/master/_autodocs/00-START-HERE.md Provides the essential commands to add Freezed and build_runner to your project's dependencies and set up the code generation watcher. ```bash # Add to pubspec.yaml flutter pub add freezed_annotation flutter pub add dev:freezed dev:build_runner # Run code generator dart run build_runner watch -d ``` -------------------------------- ### Freezed Annotation Usage Example Source: https://github.com/rrousselgit/freezed/blob/master/_autodocs/annotations.md Example demonstrating the usage of the @Freezed annotation with custom parameters like unionKey, copyWith, and equal. It also shows how to define a union type and integrate with json_serializable. ```dart import 'package:freezed_annotation/freezed_annotation.dart'; part 'user.freezed.dart'; part 'user.g.dart'; @Freezed(unionKey: 'type', copyWith: true, equal: true) sealed class User with _$User { const factory User(String name, int age) = _User; factory User.fromJson(Map json) => _$UserFromJson(json); } void main() { var user = User('Alice', 30); var updated = user.copyWith(age: 31); print(updated); // User(name: Alice, age: 31) } ``` -------------------------------- ### Freezed with Custom Lint Configuration Source: https://github.com/rrousselgit/freezed/blob/master/_autodocs/api-overview.md Example configuration for pubspec.yaml to include Freezed, build_runner, and custom linting tools for enhanced code quality checks. ```yaml # pubspec.yaml dev_dependencies develop_dependencies: freezed: ^4.0.0 build_runner: ^2.3.3 freezed_lint: latest custom_lint: ^0.5.0 ``` -------------------------------- ### Assert Annotation Usage Example Source: https://github.com/rrousselgit/freezed/blob/master/_autodocs/annotations.md Example showing how to use the @Assert annotation to enforce constraints on constructor parameters, such as non-empty name and non-negative age. ```dart @freezed abstract class Person with _$Person { @Assert('name.trim().isNotEmpty', 'name cannot be empty') @Assert('age >= 0', 'age must be non-negative') const factory Person({ required String name, required int age, }) = _Person; } ``` -------------------------------- ### Dart User toJson Example Source: https://github.com/rrousselgit/freezed/blob/master/_autodocs/generated-methods.md Shows how to serialize a User object into a JSON-serializable map using the generated toJson method. ```dart @freezed class User with _$User { const factory User(String name, int age) = _User; factory User.fromJson(Map json) => _$UserFromJson(json); } void main() { var user = User('Alice', 30); var json = user.toJson(); print(json); // {name: Alice, age: 30} } ``` -------------------------------- ### JSON Serialization with Freezed Source: https://github.com/rrousselgit/freezed/blob/master/_autodocs/usage-patterns.md Shows how to enable JSON serialization for Freezed classes using `freezed_annotation` and `json_serializable`. Includes deserialization and serialization examples. ```dart import 'package:freezed_annotation/freezed_annotation.dart'; part 'user.freezed.dart'; part 'user.g.dart'; @freezed class User with _$User { const factory User({ required String id, required String name, @JsonKey(name: 'email_address') required String email, }) = _User; factory User.fromJson(Map json) => _$UserFromJson(json); } void main() { // Deserialize var json = { 'id': '123', 'name': 'Alice', 'email_address': 'alice@example.com', }; var user = User.fromJson(json); // Serialize var output = user.toJson(); print(output); // {id: 123, name: Alice, email_address: alice@example.com} } ``` -------------------------------- ### Monorepo Workspace Configuration Source: https://github.com/rrousselgit/freezed/blob/master/_autodocs/project-setup.md Define the workspace in the root pubspec.yaml to include multiple packages in a monorepo setup. ```yaml workspace: - packages/common - packages/api - packages/app ``` -------------------------------- ### Configure Pattern Matching Methods Globally Source: https://github.com/rrousselgit/freezed/blob/master/_autodocs/configuration.md Set global options for generating pattern matching methods (`when`, `map`, `whenOrNull`, `mapOrNull`, `maybeWhen`, `maybeMap`) via `build.yaml`. This example disables `when_or_null` and `map` variants. ```yaml # build.yaml targets: $default: builders: freezed: options: when: when: true when_or_null: false maybe_when: false map: map: false map_or_null: false maybe_map: false ``` -------------------------------- ### Custom Freezed build.yaml Configuration Source: https://github.com/rrousselgit/freezed/blob/master/_autodocs/project-setup.md Customize Freezed behavior using build.yaml options. This example shows custom formatting, union case, and disabling maybe_when. ```yaml targets: $default: builders: freezed: options: format: true union_value_case: pascal when: maybe_when: false ``` -------------------------------- ### Map Method with CopyWith Example Source: https://github.com/rrousselgit/freezed/blob/master/packages/freezed/README.md Demonstrates using the 'map' method to apply operations like 'copyWith' to specific states of a sealed class. ```dart model.map( first: (value) => value, second: (value) => value.copyWith(c: true), ) ``` -------------------------------- ### Model with Map Method Example Source: https://github.com/rrousselgit/freezed/blob/master/packages/freezed/README.md Illustrates the 'map' method for handling different states of a sealed class without destructuring, useful for complex operations. ```dart model.map( first: (First value) => 'first ${value.a}', second: (Second value) => 'second ${value.b} ${value.c}' ) ``` -------------------------------- ### EqualUnmodifiableSetView Usage Example Source: https://github.com/rrousselgit/freezed/blob/master/_autodocs/collection-types.md Demonstrates using EqualUnmodifiableSetView for a set of integers in a Freezed class. Shows that instances with the same content are equal and attempting to modify the set throws an error. ```dart @freezed class UniqueItems with _$UniqueItems { factory UniqueItems(Set ids) = _UniqueItems; } void main() { var items1 = UniqueItems({1, 2, 3}); var items2 = UniqueItems({1, 2, 3}); print(items1 == items2); // true items1.ids.add(4); // throws UnsupportedError } ``` -------------------------------- ### Freezed Import with JSON Serialization Source: https://github.com/rrousselgit/freezed/blob/master/_autodocs/api-overview.md This import setup includes necessary parts for both Freezed code generation and JSON serialization using json_serializable. ```dart import 'package:freezed_annotation/freezed_annotation.dart'; part 'file.freezed.dart'; part 'file.g.dart'; ``` -------------------------------- ### Dart Freezed Usage Example with hashCode Source: https://github.com/rrousselgit/freezed/blob/master/_autodocs/generated-methods.md Demonstrates how Freezed generates hashCode for value equality, allowing objects to be correctly used in sets and maps by removing duplicates. ```dart @freezed class User with _$User { const factory User(String name, int age) = _User; } void main() { var user1 = User('Alice', 30); var user2 = User('Alice', 30); print(user1.hashCode == user2.hashCode); // true // Can be used in sets/maps var users = {user1, user2}; print(users.length); // 1 (duplicates removed) } ``` -------------------------------- ### Mutating Collections Example Source: https://github.com/rrousselgit/freezed/blob/master/packages/freezed/README.md Demonstrates successful mutation of a `List` property when `makeCollectionsUnmodifiable` is set to `false` in the `@Freezed` annotation. ```dart void main() { var example = Example([]); example.list.add(42); // OK } ``` -------------------------------- ### Dart Freezed when Pattern Matching Example Source: https://github.com/rrousselgit/freezed/blob/master/_autodocs/generated-methods.md Illustrates how to use the `when` method for pattern matching on Freezed union types, providing specific callbacks for each constructor. ```dart @freezed sealed class State with _$State { factory State.loading() = Loading; factory State.success(String data) = Success; factory State.error(String message) = Error; } void main() { var state = State.success('done'); var message = state.when( loading: () => 'Loading...', success: (data) => 'Got: $data', error: (message) => 'Error: $message', ); print(message); // Got: done } ``` -------------------------------- ### copyWith Usage Example Source: https://github.com/rrousselgit/freezed/blob/master/_autodocs/generated-methods.md Demonstrates creating new instances with updated properties using the generated copyWith method. The original object remains unchanged. ```dart @freezed class User with _$User { const factory User(String name, int age) = _User; } void main() { var user = User('Alice', 30); // Create copy with updated name var updated = user.copyWith(name: 'Bob'); print(updated); // User(name: Bob, age: 30) // Original is unchanged print(user); // User(name: Alice, age: 30) // Can update multiple properties var aged = user.copyWith(name: 'Charlie', age: 31); print(aged); // User(name: Charlie, age: 31) } ``` -------------------------------- ### Configure Map Methods Generation Source: https://github.com/rrousselgit/freezed/blob/master/_autodocs/annotations.md Use FreezedMapOptions to control the generation of 'map', 'mapOrNull', and 'maybeMap' methods. This example enables 'map' and 'mapOrNull' while disabling 'maybeMap'. ```dart @Freezed(map: FreezedMapOptions(map: true, mapOrNull: true, maybeMap: false)) sealed class Event with _$Event { factory Event.userCreated(String userId) = UserCreated; factory Event.userDeleted(String userId) = UserDeleted; } ``` -------------------------------- ### Dart Freezed Collection Hash Codes Example Source: https://github.com/rrousselgit/freezed/blob/master/_autodocs/generated-methods.md Illustrates Freezed's generation of hash codes for classes containing collections, ensuring that instances with identical collection contents are considered equal. ```dart @freezed class Data with _$Data { factory Data(List items) = _Data; } void main() { var d1 = Data(['a', 'b']); var d2 = Data(['a', 'b']); print(d1.hashCode == d2.hashCode); // true } ``` -------------------------------- ### Dart Freezed map Pattern Matching Example Source: https://github.com/rrousselgit/freezed/blob/master/_autodocs/generated-methods.md Shows how to use the `map` method for pattern matching on Freezed union types, where callbacks receive the instance of the matched constructor. ```dart @freezed sealed class Event with _$Event { factory Event.userCreated(String userId) = UserCreated; factory Event.userDeleted(String userId) = UserDeleted; } void main() { var event = Event.userCreated('123'); var processed = event.map( userCreated: (e) => 'Created user ${e.userId}', userDeleted: (e) => 'Deleted user ${e.userId}', ); print(processed); // Created user 123 } ``` -------------------------------- ### EqualUnmodifiableMapView Usage Example Source: https://github.com/rrousselgit/freezed/blob/master/_autodocs/collection-types.md Demonstrates using EqualUnmodifiableMapView for a map of strings to dynamic in a Freezed class. Shows that instances with the same content are equal and attempting to modify the map throws an error. ```dart @freezed class Config with _$Config { factory Config(Map settings) = _Config; } void main() { var config1 = Config({'theme': 'dark', 'lang': 'en'}); var config2 = Config({'theme': 'dark', 'lang': 'en'}); print(config1 == config2); // true config1.settings['theme'] = 'light'; // throws UnsupportedError } ``` -------------------------------- ### EqualUnmodifiableListView Usage Example Source: https://github.com/rrousselgit/freezed/blob/master/_autodocs/collection-types.md Demonstrates using EqualUnmodifiableListView for a list of strings in a Freezed class. Shows that instances with the same content are equal and attempting to modify the list throws an error. ```dart @freezed class Items with _$Items { factory Items(List tags) = _Items; } void main() { var items1 = Items(['a', 'b']); var items2 = Items(['a', 'b']); print(items1 == items2); // true (uses EqualUnmodifiableListView equality) items1.tags.add('c'); // throws UnsupportedError } ``` -------------------------------- ### Dart Freezed toString Usage Example Source: https://github.com/rrousselgit/freezed/blob/master/_autodocs/generated-methods.md Shows the default string representation generated by Freezed for a class, which includes all properties and their values in a readable format. ```dart @freezed class User with _$User { const factory User(String name, int age) = _User; } void main() { var user = User('Alice', 30); print(user); // _User(name: Alice, age: 30) } ``` -------------------------------- ### Complete Immutable Class with JSON Serialization Source: https://github.com/rrousselgit/freezed/blob/master/_autodocs/00-START-HERE.md Illustrates a complete Freezed class definition including imports, part files, JSON serialization/deserialization, and usage examples for creation, copying, equality, and JSON handling. ```dart import 'package:freezed_annotation/freezed_annotation.dart'; part 'user.freezed.dart'; part 'user.g.dart'; @freezed class User with _$User { const factory User({ required String id, required String name, required int age, }) = _User; factory User.fromJson(Map json) => _$UserFromJson(json); } void main() { // Create var user = User(id: '1', name: 'Alice', age: 30); // Copy with modification var older = user.copyWith(age: 31); // Equality (value-based) print(user == User(id: '1', name: 'Alice', age: 30)); // true // JSON var json = user.toJson(); // Serialize var restored = User.fromJson(json); // Deserialize } ``` -------------------------------- ### Minimal Immutable Class Example Source: https://github.com/rrousselgit/freezed/blob/master/_autodocs/README.md Demonstrates the basic usage of Freezed to create an immutable class with essential features like value equality and cloning. This is useful for defining simple data structures. ```dart import 'package:freezed_annotation/freezed_annotation.dart'; part 'user.freezed.dart'; @freezed class User with _$User { const factory User({ required String id, required String name, }) = _User; } void main() { var user = User(id: '1', name: 'Alice'); print(user); // _User(id: 1, name: Alice) var updated = user.copyWith(name: 'Bob'); print(updated == user); // false } ``` -------------------------------- ### Clean and Rebuild Project Source: https://github.com/rrousselgit/freezed/blob/master/_autodocs/project-setup.md Perform a clean build by removing generated files and lock files, then reinstalling dependencies. ```bash rm -rf .dart_tool/ rm -f pubspec.lock dart pub get dart run build_runner clean dart run build_runner build -d ``` -------------------------------- ### Solution: Ensure Correct Part Directives for File Generation Source: https://github.com/rrousselgit/freezed/blob/master/_autodocs/project-setup.md Verify that your files include the correct import and part directives for Freezed to generate the necessary files. ```dart import 'package:freezed_annotation/freezed_annotation.dart'; part 'filename.freezed.dart'; ``` -------------------------------- ### Const 'freezed' Annotation Usage Source: https://github.com/rrousselgit/freezed/blob/master/_autodocs/annotations.md Example of using the @freezed annotation for defining an immutable class. ```dart @freezed abstract class Person with _$Person { const factory Person(String name, int age) = _Person; } ``` -------------------------------- ### Solution: Clean and Rebuild for Null Safety or Interrupted Builds Source: https://github.com/rrousselgit/freezed/blob/master/_autodocs/project-setup.md Address null safety mismatches or interrupted build processes by cleaning old generated files and rebuilding. ```bash dart pub get dart run build_runner clean # Clean old generated files dart run build_runner build ``` -------------------------------- ### Basic Sealed Class Syntax Source: https://github.com/rrousselgit/freezed/blob/master/_autodocs/union-types-sealed-classes.md Illustrates the basic syntax for creating a sealed class with two distinct implementations using factory constructors and explicit implementation names. ```dart @freezed sealed class MyUnion with _$MyUnion { // Use 'factory' keyword for constructors const factory MyUnion.first(String a) = FirstImpl; const factory MyUnion.second(int b, bool c) = SecondImpl; } ``` -------------------------------- ### Freezed Convenience Constant for Immutable Classes Source: https://github.com/rrousselgit/freezed/blob/master/_autodocs/configuration.md Use the 'freezed' constant for a pre-configured immutable Freezed class setup. ```dart const freezed = Freezed(); ``` ```dart @Freezed( equal: true, copyWith: true, toStringOverride: true, makeCollectionsUnmodifiable: true, addImplicitFinal: true, ) ``` ```dart @freezed class User with _$User { const factory User(String name, int age) = _User; } ``` -------------------------------- ### Run Build Runner with Verbose Output Source: https://github.com/rrousselgit/freezed/blob/master/_autodocs/project-setup.md Execute the build runner in watch mode with verbose logging enabled to see detailed output during the generation process. ```bash dart run build_runner watch -d -v ``` -------------------------------- ### Dart Union Type Serialization Example Source: https://github.com/rrousselgit/freezed/blob/master/_autodocs/generated-methods.md Illustrates how to serialize a union type (Result) into a JSON map, including the runtimeType. ```dart @freezed sealed class Result with _$Result { const factory Result.success(T value) = Success; const factory Result.error(String message) = Error; factory Result.fromJson(Map json) => _$ResultFromJson(json); } void main() { var result = Result.success(42); var json = result.toJson(); print(json); // {runtimeType: success, value: 42} } ``` -------------------------------- ### build.yaml for Project-Wide Freezed Configuration Source: https://github.com/rrousselgit/freezed/blob/master/packages/freezed/README.md Configures Freezed behavior for the entire project by setting 'format', 'copy_with', and 'equal' options in the build.yaml file. ```yaml targets: $default: builders: freezed: options: # Tells Freezed to format .freezed.dart files. # This can significantly slow down code-generation. # Disabling formatting will only work when opting into Dart 3.7 as a minimum # in your project SDK constraints. format: true # Disable the generation of copyWith/== for the entire project copy_with: false equal: false ``` -------------------------------- ### Solution: Run Build Runner to Create Generated Files Source: https://github.com/rrousselgit/freezed/blob/master/_autodocs/project-setup.md If you encounter the 'The part directive is not importing a file' error, run the build runner to generate the missing files. ```bash dart run build_runner build ``` -------------------------------- ### Const 'unfreezed' Annotation Usage Source: https://github.com/rrousselgit/freezed/blob/master/_autodocs/annotations.md Example demonstrating the use of the @unfreezed annotation for a mutable class, allowing modification of properties. ```dart @unfreezed abstract class MutablePerson with _$MutablePerson { factory MutablePerson(String name, int age) = _MutablePerson; } void main() { var person = MutablePerson('Alice', 30); person.name = 'Bob'; // Allowed because class is mutable } ``` -------------------------------- ### Build.yaml Configuration for Union Key and Case Source: https://github.com/rrousselgit/freezed/blob/master/packages/freezed/README.md Configures the 'freezed' builder globally in build.yaml to set the union key and value case for all Freezed classes. ```yaml targets: $default: builders: freezed: options: union_key: type union_value_case: pascal ``` -------------------------------- ### Freezed Convenience Constant for Mutable Classes Source: https://github.com/rrousselgit/freezed/blob/master/_autodocs/configuration.md Use the 'unfreezed' constant for a pre-configured mutable Freezed class setup, allowing property modification. ```dart const unfreezed = Freezed( equal: false, addImplicitFinal: false, makeCollectionsUnmodifiable: false, ) ``` ```dart @unfreezed class MutableUser with _$MutableUser { factory MutableUser(String name, int age) = _MutableUser; } ``` ```dart void main() { var user = MutableUser('Alice', 30); user.name = 'Bob'; // Allowed } ``` -------------------------------- ### Basic Freezed Class Definition Source: https://github.com/rrousselgit/freezed/blob/master/packages/freezed/README.md Defines a basic abstract class with the @freezed decorator. This is the starting point for creating immutable classes with Freezed. ```dart abstract class Person with _$Person { const factory Person({ String? name, int? age, Gender? gender, }) = _Person; } ``` -------------------------------- ### Type-Safe Builders with Freezed Source: https://github.com/rrousselgit/freezed/blob/master/_autodocs/advanced-features.md Shows how to create fluent builder interfaces using Freezed classes and a custom builder pattern for type-safe object construction. ```dart @freezed class QueryRequest with _$QueryRequest { const factory QueryRequest({ @Default('') String search, @Default([]) List filters, @Default(1) int page, @Default(20) int pageSize, }) = _QueryRequest; } class QueryBuilder { final QueryRequest _request; QueryBuilder() : _request = const QueryRequest(); QueryBuilder._from(this._request); QueryBuilder search(String term) => QueryBuilder._from(_request.copyWith(search: term)); QueryBuilder addFilter(String filter) => QueryBuilder._from( _request.copyWith( filters: [..._request.filters, filter], ), ); QueryBuilder page(int pageNum) => QueryBuilder._from(_request.copyWith(page: pageNum)); QueryBuilder pageSize(int size) => QueryBuilder._from(_request.copyWith(pageSize: size)); QueryRequest build() => _request; } void main() { var request = QueryBuilder() .search('flutter') .addFilter('tag:tutorial') .addFilter('stars:>100') .page(2) .pageSize(50) .build(); print(request); // QueryRequest( // search: flutter, // filters: [tag:tutorial, stars:>100], // page: 2, // pageSize: 50, // ) } ``` -------------------------------- ### Run Build Runner in Watch Mode Source: https://github.com/rrousselgit/freezed/blob/master/_autodocs/project-setup.md Use watch mode to automatically regenerate code when files change, improving development speed. ```bash dart run build_runner watch -d ``` -------------------------------- ### Enable Automatic Code Formatting Source: https://github.com/rrousselgit/freezed/blob/master/_autodocs/configuration.md Configure Freezed to automatically format generated code. This improves readability but may slightly increase code generation time. Set via `build.yaml`. ```yaml # build.yaml targets: $default: builders: freezed: options: format: true ``` -------------------------------- ### Equality Operator Usage Example Source: https://github.com/rrousselgit/freezed/blob/master/_autodocs/generated-methods.md Demonstrates the generated equality operator for comparing instances of a Freezed class. Two instances are equal if all their properties match. ```dart @freezed class Point with _$Point { const factory Point(double x, double y) = _Point; } void main() { var p1 = Point(3.0, 4.0); var p2 = Point(3.0, 4.0); var p3 = Point(3.0, 5.0); print(p1 == p2); // true (same values) print(p1 == p3); // false (different y) } ``` -------------------------------- ### Accessing Shared Properties in Main Source: https://github.com/rrousselgit/freezed/blob/master/_autodocs/union-types-sealed-classes.md Demonstrates how to create instances of different variants of a sealed class with shared properties and access those shared properties. ```dart void main() { var event = UserCreated('123', DateTime.now()); print(event.timestamp); // Access shared property var another = UserDeleted('456', DateTime.now()); print(another.timestamp); // Works on all variants } ``` -------------------------------- ### Configure Union Value Case for JSON Encoding Source: https://github.com/rrousselgit/freezed/blob/master/_autodocs/configuration.md Set the casing convention for union constructor names when encoding to JSON. This example uses PascalCase. ```dart @Freezed(unionValueCase: FreezedUnionCase.pascal) sealed class State with _$State { factory State.initializing() = Initializing; factory State.loadingData() = LoadingData; factory State.fromJson(Map json) = _$StateFromJson(json); } void main() { var state = LoadingData(); print(state.toJson()); // {runtimeType: LoadingData} // Pascal case } ``` -------------------------------- ### analysis_options.yaml Configuration for Freezed Source: https://github.com/rrousselgit/freezed/blob/master/_autodocs/project-setup.md Configure analysis_options.yaml to ignore warnings for generated Freezed files and disable specific linter rules. ```yaml analyzer: errors: invalid_annotation_target: ignore exclude: - "**/*.freezed.dart" - "**/*.g.dart" linter: rules: - avoid_private_typedef_functions - avoid_returning_null_for_future ``` -------------------------------- ### Mutable Class Property Example Source: https://github.com/rrousselgit/freezed/blob/master/packages/freezed/README.md Demonstrates mutating properties of a class defined with `@unfreezed`. Note that mutable classes do not have custom `==/hashCode` implementations and cannot be instantiated with `const`. ```dart void main() { var person = Person(firstName: 'John', lastName: 'Smith'); person.firstName = 'Mona'; person.lastName = 'Lisa'; } ``` -------------------------------- ### FreezedWhenOptions Configuration Source: https://github.com/rrousselgit/freezed/blob/master/_autodocs/annotations.md Shows the definition of the FreezedWhenOptions class, used for configuring the generation of 'when', 'whenOrNull', and 'maybeWhen' methods. ```dart class FreezedWhenOptions { const FreezedWhenOptions({ bool? when, bool? whenOrNull, bool? maybeWhen, }); final bool? when; final bool? whenOrNull; final bool? maybeWhen; static const all = FreezedWhenOptions( when: true, whenOrNull: true, maybeWhen: true, ); static const none = FreezedWhenOptions( when: false, whenOrNull: false, maybeWhen: false, ); } ``` -------------------------------- ### Build Runner Commands Source: https://github.com/rrousselgit/freezed/blob/master/_autodocs/README.md Provides essential commands for running the Freezed code generator using `build_runner`. Use watch mode for development and one-time builds for production or CI. ```bash # Watch mode (recommended for development) dart run build_runner watch -d # One-time build dart run build_runner build # Clean and rebuild dart run build_runner clean dart run build_runner build ``` -------------------------------- ### Controlling Union Case with @FreezedUnionCase Source: https://github.com/rrousselgit/freezed/blob/master/_autodocs/annotations.md Demonstrates how to use @FreezedUnionCase to control the transformation of union constructor names in JSON serialization, using Pascal case in this example. ```dart @Freezed(unionValueCase: FreezedUnionCase.pascal) sealed class Response with _$Response { factory Response.success(String data) = Success; factory Response.error(String message) = Error; factory Response.fromJson(Map json) => _$ResponseFromJson(json); } void main() { var response = Success('hello'); print(response.toJson()); // {'runtimeType': 'Success', 'data': 'hello'} } ``` -------------------------------- ### Default Values with Freezed Source: https://github.com/rrousselgit/freezed/blob/master/_autodocs/usage-patterns.md Shows how to define default values for properties in Freezed classes using the `@Default()` annotation. Demonstrates creating instances with and without explicit values. ```dart @freezed class Counter with _$Counter { const factory Counter({ @Default(0) int count, @Default('') String label, }) = _Counter; } void main() { var counter1 = Counter(); print(counter1.count); // 0 print(counter1.label); // '' var counter2 = Counter(count: 5); print(counter2.count); // 5 } ``` -------------------------------- ### Deep Collection Equality Usage Example Source: https://github.com/rrousselgit/freezed/blob/master/_autodocs/collection-types.md Illustrates automatic deep equality for nested lists within a Freezed DataContainer class, utilizing the re-exported DeepCollectionEquality. ```dart @freezed class DataContainer with _$DataContainer { factory DataContainer(List> matrix) = _DataContainer; } void main() { var container1 = DataContainer([[1, 2], [3, 4]]); var container2 = DataContainer([[1, 2], [3, 4]]); // Automatic deep equality for nested lists print(container1 == container2); // true } ``` -------------------------------- ### Run Build Runner in Watch Mode Source: https://github.com/rrousselgit/freezed/blob/master/_autodocs/project-setup.md Automatically regenerate files when changes are detected. Use the -d flag for delete mode, which removes generated files when the source is deleted. ```bash dart run build_runner watch -d # or for Flutter flutter pub run build_runner watch -d ``` -------------------------------- ### Define a Union Type with Freezed Source: https://github.com/rrousselgit/freezed/blob/master/packages/freezed/README.md Defines a sealed union type 'Example' with two cases: 'Person' and 'City'. This is the basic structure for creating union types with Freezed. ```dart sealed class Example with _$Example { const factory Example.person(String name, int age) = Person; const factory Example.city(String name, int population) = City; } ``` -------------------------------- ### Mutable Class Equality Example Source: https://github.com/rrousselgit/freezed/blob/master/packages/freezed/README.md Illustrates that mutable classes created with `@unfreezed` do not generate custom equality operators, resulting in `false` for comparisons of objects with identical values. ```dart void main() { var john = Person(firstName: 'John', lastName: 'Smith'); var john2 = Person(firstName: 'John', lastName: 'Smith'); print(john == john2); // false } ``` -------------------------------- ### Disable Specific Pattern Matching Methods Source: https://github.com/rrousselgit/freezed/blob/master/_autodocs/configuration.md Control which specific pattern matching methods (`when`, `whenOrNull`, `maybeWhen`) are generated for a sealed class. This example disables `whenOrNull` and `maybeWhen`. ```dart @Freezed( when: FreezedWhenOptions( when: true, whenOrNull: false, maybeWhen: false, ), ) sealed class State with _$State { ... } ``` -------------------------------- ### Deep copyWith Usage Example Source: https://github.com/rrousselgit/freezed/blob/master/_autodocs/generated-methods.md Demonstrates deep copying by chaining copyWith calls to update properties of nested objects. Provides an alternative to traditional nested copyWith. ```dart @freezed class Company with _$Company { const factory Company({ required String name, required Director director, }) = _Company; } @freezed class Director with _$Director { const factory Director({ required String name, required Assistant? assistant, }) = _Director; } @freezed class Assistant with _$Assistant { const factory Assistant(String name) = _Assistant; } void main() { var company = Company( name: 'Tech Corp', director: Director( name: 'Alice', assistant: Assistant('Bob'), ), ); // Deep copy: change the assistant name var updated = company.copyWith.director.assistant(name: 'Charlie'); // Result: Company with updated assistant name // Alternative: use traditional nested copyWith var updated2 = company.copyWith( director: company.director.copyWith( assistant: company.director.assistant.copyWith(name: 'Charlie'), ), ); // Same result, more verbose } ``` -------------------------------- ### Add JSON Serialization Dependencies Source: https://github.com/rrousselgit/freezed/blob/master/_autodocs/project-setup.md Add the necessary dependencies for JSON serialization using json_annotation and json_serializable. ```bash flutter pub add json_annotation dev:json_serializable ``` -------------------------------- ### Pattern Matching with Switch Expressions Source: https://github.com/rrousselgit/freezed/blob/master/_autodocs/union-types-sealed-classes.md Utilizes Dart's modern `switch` expression with sealed classes for exhaustive pattern matching. This example matches on different `Weather` states. ```dart @freezed sealed class Weather with _$Weather { const factory Weather.sunny(int temperature) = Sunny; const factory Weather.rainy(double humidity) = Rainy; const factory Weather.snowy(String blizzardWarning) = Snowy; } void displayWeather(Weather weather) { switch (weather) { case Sunny(:final temperature): print('Sunny, ${temperature}°C'); case Rainy(:final humidity): print('Rainy, ${humidity}% humidity'); case Snowy(:final blizzardWarning): print('Snowy: $blizzardWarning'); } } ``` -------------------------------- ### Run Build Runner with Delete Mode Source: https://github.com/rrousselgit/freezed/blob/master/_autodocs/project-setup.md Enable delete mode to remove generated files that are no longer needed. ```bash dart run build_runner build -d ``` ```bash dart run build_runner watch -d ``` -------------------------------- ### GitHub Actions for Code Generation Source: https://github.com/rrousselgit/freezed/blob/master/_autodocs/project-setup.md Set up a GitHub Actions workflow to automatically generate code on pull requests. ```yaml name: Generate Code on: pull_request: paths: - '**.dart' jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: dart-lang/setup-dart@v1 with: sdk: stable - run: dart pub get - run: dart run build_runner build - run: git diff --exit-code ``` -------------------------------- ### Dart Freezed Union Type toString Example Source: https://github.com/rrousselgit/freezed/blob/master/_autodocs/generated-methods.md Demonstrates the string representation for union types (sealed classes) generated by Freezed, clearly indicating the specific subtype and its values. ```dart @freezed sealed class Result with _$Result { const factory Result.success(T value) = Success; const factory Result.error(String message) = Error; } void main() { var success = Result.success(42); var error = Result.error('failed'); print(success); // Success(value: 42) print(error); // Error(message: failed) } ``` -------------------------------- ### Freezed Builder Function Source: https://github.com/rrousselgit/freezed/blob/master/_autodocs/api-overview.md The entry point for the build_runner code generator. It sets up the PartBuilder with the FreezedGenerator and specifies the output file format and header. ```dart Builder freezed(BuilderOptions options) { return PartBuilder( [FreezedGenerator(...)], '.freezed.dart', formatOutput: _defaultFormatOutput, header: '// GENERATED CODE - DO NOT MODIFY BY HAND', ); } ``` -------------------------------- ### Custom Equality Behavior Source: https://github.com/rrousselgit/freezed/blob/master/_autodocs/advanced-features.md Overrides the default equality (`==`) and `hashCode` behavior to define custom comparison logic. This example shows equality based only on the 'id' field, ignoring the 'name' field. ```dart @freezed class Entity with _$Entity { const Entity._(); const factory Entity({ required String id, required String name, }) = _Entity; // Equality based only on ID (not name) @override bool operator ==(Object other) => other is Entity && other.id == id; @override int get hashCode => id.hashCode; } void main() { var entity1 = Entity(id: '1', name: 'Alice'); var entity2 = Entity(id: '1', name: 'Bob'); print(entity1 == entity2); // true (same ID, different name) } ``` -------------------------------- ### Configure Generic Argument Factories in build.yaml Source: https://github.com/rrousselgit/freezed/blob/master/packages/freezed/README.md Alternatively, enable `genericArgumentFactories` for the entire project by modifying your `build.yaml` file. ```yaml targets: $default: builders: freezed: options: generic_argument_factories: true ``` -------------------------------- ### Define Immutable Class and Generated Methods Source: https://github.com/rrousselgit/freezed/blob/master/_autodocs/00-START-HERE.md Demonstrates the basic definition of an immutable class using the @freezed annotation and shows examples of generated methods like copyWith, value equality, and toString. ```dart // Define immutable class @freezed class User with _$User { const factory User({ required String name, required int age, }) = _User; } // Generated methods: User('Alice', 30).copyWith(age: 31); // Copy with modification User('Alice', 30) == User('Alice', 30); // Value equality User('Alice', 30).toString(); // Debug string ``` -------------------------------- ### Custom Union and Code Generation Options Source: https://github.com/rrousselgit/freezed/blob/master/_autodocs/configuration.md Configure union types, JSON serialization, copyWith, equality, and string overrides for sealed classes. This example demonstrates advanced customization for API response handling. ```dart @Freezed( unionKey: 'type', unionValueCase: FreezedUnionCase.snake, fallbackUnion: 'unknown', copyWith: true, equal: true, toStringOverride: true, makeCollectionsUnmodifiable: true, when: FreezedWhenOptions.all, map: FreezedMapOptions(map: true, mapOrNull: true, maybeMap: false), ) sealed class ApiResponse with _$ApiResponse { const factory ApiResponse.loading() = ApiResponseLoading; const factory ApiResponse.success(T data) = ApiResponseSuccess; const factory ApiResponse.error(String message) = ApiResponseError; const factory ApiResponse.unknown(Map data) = ApiResponseUnknown; factory ApiResponse.fromJson( Map json, T Function(Object?) fromJsonT, ) => _$ApiResponseFromJson(json, fromJsonT); } ``` -------------------------------- ### Pattern Matching with when (Legacy) Source: https://github.com/rrousselgit/freezed/blob/master/_autodocs/usage-patterns.md Demonstrates the legacy `when` method for pattern matching on union types. This method is useful for handling all possible states of a sealed class. ```dart @freezed sealed class ApiResponse with _$ApiResponse { factory ApiResponse.success(String data) = SuccessResponse; factory ApiResponse.error(String message) = ErrorResponse; factory ApiResponse.timeout() = TimeoutResponse; } void handleResponse(ApiResponse response) { response.when( success: (data) => print('Success: $data'), error: (message) => print('Error: $message'), timeout: () => print('Request timed out'), ); } ``` -------------------------------- ### Global Freezed Configuration in build.yaml Source: https://github.com/rrousselgit/freezed/blob/master/_autodocs/configuration.md Apply default Freezed generation settings across all classes in your project by creating a build.yaml file. ```yaml targets: $default: builders: freezed: enabled: true options: # Code generation format: false # Set to true to format generated code # Methods copy_with: true equal: true to_string_override: true from_json: null to_json: null # Annotations add_implicit_final: true make_collections_unmodifiable: true generic_argument_factories: false # Union types union_key: runtimeType union_value_case: null fallback_union: null # Pattern matching when: when: true when_or_null: true maybe_when: true map: map: true map_or_null: true maybe_map: true ``` -------------------------------- ### Ejecting a Union Case with a Freezed Class Source: https://github.com/rrousselgit/freezed/blob/master/README.md Shows how to manually define a union case as a Freezed class, providing fine-grained control. This example defines 'ResultData' as a Freezed class extending the base 'Result' union. ```dart @freezed abstract class ResultData extends Result with _$ResultData { const factory ResultData(T data) = _ResultData; const ResultData._() : super._(); } ``` -------------------------------- ### Monorepo Package Build Configuration Source: https://github.com/rrousselgit/freezed/blob/master/_autodocs/project-setup.md Configure Freezed builder options for a specific package within a monorepo. ```yaml targets: $default: builders: freezed: options: format: true ``` -------------------------------- ### Testing Union Types with `test` package Source: https://github.com/rrousselgit/freezed/blob/master/_autodocs/union-types-sealed-classes.md Write unit tests for sealed classes using Dart's `test` package. Examples demonstrate testing success and error cases, and using `maybeWhen` for pattern matching. ```dart import 'package:test/test.dart'; void main() { group('Result', () { test('success case', () { var result = Result.success('hello'); expect(result, isA()); expect((result as Success).data, equals('hello')); }); test('pattern matching', () { var result = Result.error('oops'); var message = result.maybeWhen( error: (msg) => 'Error: $msg', orElse: () => 'Unknown', ); expect(message, equals('Error: oops')); }); }); } ``` -------------------------------- ### State Management with Sealed Classes Source: https://github.com/rrousselgit/freezed/blob/master/_autodocs/usage-patterns.md Demonstrates using Freezed's sealed classes for managing application state, providing a clear and type-safe way to represent different states. ```dart import 'package:freezed_annotation/freezed_annotation.dart'; part 'user_state.freezed.dart'; // Assuming User class is defined elsewhere class User {} @freezed sealed class UserState with _$UserState { const factory UserState.initial() = UserStateInitial; const factory UserState.loading() = UserStateLoading; const factory UserState.success(User user) = UserStateSuccess; const factory UserState.error(String message) = UserStateError; } // In a provider or BLoC UserState state = UserStateInitial(); void fetchUser() { state = UserStateLoading(); try { // Assuming api.getUser() is an async function that returns a User // var user = await api.getUser(); // state = UserStateSuccess(user); } catch (e) { state = UserStateError(e.toString()); } } ``` -------------------------------- ### Define a Sealed Class with Freezed Source: https://github.com/rrousselgit/freezed/blob/master/_autodocs/union-types-sealed-classes.md Use the `@freezed` annotation and `sealed class` keyword to define a sealed class with multiple factory constructors representing different states or types. This example defines a generic `Result` type. ```dart import 'package:freezed_annotation/freezed_annotation.dart'; part 'result.freezed.dart'; @freezed sealed class Result with _$Result { const factory Result.success(T data) = Success; const factory Result.error(String message) = Error; const factory Result.loading() = Loading; } ``` -------------------------------- ### Union Types (Sum Types) Example Source: https://github.com/rrousselgit/freezed/blob/master/_autodocs/README.md Illustrates the creation and usage of union types (also known as sum types or sealed classes) with Freezed, enabling type-safe pattern matching. This is useful for representing states or distinct outcomes. ```dart @freezed sealed class Result with _$Result { const factory Result.success(T data) = Success; const factory Result.error(String message) = Error; } void main() { Result result = Success('hello'); switch (result) { case Success(:final data): print('Success: $data'); case Error(:final message): print('Error: $message'); } } ``` -------------------------------- ### Run Dart Analyze Source: https://github.com/rrousselgit/freezed/blob/master/_autodocs/project-setup.md Execute the dart analyze command to check your code against custom lint rules. ```bash dart analyze ``` -------------------------------- ### Builder Pattern with copyWith Source: https://github.com/rrousselgit/freezed/blob/master/_autodocs/usage-patterns.md Demonstrates the builder pattern using Freezed's `copyWith` method for creating and modifying immutable objects step-by-step. ```dart import 'package:freezed_annotation/freezed_annotation.dart'; part 'query_builder.freezed.dart'; @freezed class QueryBuilder with _$QueryBuilder { const factory QueryBuilder({ @Default('') String search, @Default(1) int page, @Default(10) int limit, @Default([]) List filters, }) = _QueryBuilder; } void main() { var query = QueryBuilder(); var withSearch = query.copyWith(search: 'flutter'); var paginated = withSearch.copyWith(page: 2); var filtered = paginated.copyWith(filters: ['tag:new']); print(filtered); // _QueryBuilder(search: flutter, page: 2, limit: 10, filters: [tag:new]) } ``` -------------------------------- ### Using 'when' with Model Class Source: https://github.com/rrousselgit/freezed/blob/master/README.md Demonstrates the 'when' method for pattern matching with destructuring on the 'Model' class. ```dart var model = Model.first('42'); print( model.when( first: (String a) => 'first $a', second: (int b, bool c) => 'second $b $c' ), ); // first 42 ``` -------------------------------- ### Reduce Build Runner Output Verbosity Source: https://github.com/rrousselgit/freezed/blob/master/_autodocs/project-setup.md Redirect standard error to /dev/null to minimize verbose output from build_runner. ```bash dart run build_runner build -d 2>/dev/null ``` -------------------------------- ### Increase Memory for Build Runner Source: https://github.com/rrousselgit/freezed/blob/master/_autodocs/project-setup.md Run build_runner with the --observe flag to increase available memory for large projects. ```bash dart --observe run build_runner build ```