
Freezed is a powerful code generation package in Flutter that simplifies state management and data modeling by automatically generating immutable classes and value objects. It leverages the `json_serializable` and `copy_with` functionalities to reduce boilerplate code, making it easier to handle complex data structures and state changes in your Flutter applications. By using Freezed, developers can ensure type safety, improve code readability, and streamline the process of managing data across widgets and screens. To get started with Freezed, you’ll need to set up the necessary dependencies in your `pubspec.yaml` file, run code generation commands, and define your data models using the `@freezed` annotation. This introduction will guide you through the essential steps to effectively integrate and utilize Freezed in your Flutter projects.
| Characteristics | Values |
|---|---|
| Purpose | Code generation for immutable classes with value equality, copyWith, and JSON serialization/deserialization |
| Installation | Add freezed and json_serializable dependencies in pubspec.yaml |
| Annotation | Use @freezed annotation on classes to generate boilerplate code |
| Code Generation | Run flutter pub run build_runner build to generate the necessary files |
| Immutability | Generates immutable classes by default, ensuring thread safety and predictability |
| Value Equality | Implements == and hashCode for value-based equality checks |
| CopyWith Method | Generates a copyWith method for creating modified copies of objects |
| JSON Support | Automatically generates toJson and fromJson methods for serialization/deserialization |
| Union Types | Supports union types using @Freezed(union: true) for handling multiple data types |
| Default Values | Allows specifying default values for fields using @Default annotation |
| Custom Constructors | Supports custom constructors and factory methods |
| Part Files | Generates .freezed.dart and .g.dart files for separating generated code |
| Integration | Works seamlessly with flutter_bloc, provider, and other state management solutions |
| Performance | Optimized for performance with minimal runtime overhead |
| Documentation | Well-documented with examples and guides available in the official repository |
| Community Support | Active community and regular updates from the maintainers |
Explore related products
What You'll Learn
- Setup Freezed: Add dependencies, install plugins, and configure build runner for code generation
- Model Creation: Define immutable classes with `@freezed` and generate boilerplate code
- CopyWith Method: Use `copyWith` to create modified instances of freezed models
- Union Types: Implement enums with `@Freezed` for handling multiple data states
- Integration: Integrate freezed with providers, BLoC, or other state management solutions

Setup Freezed: Add dependencies, install plugins, and configure build runner for code generation
Freezed, a powerful code generation tool for Flutter, simplifies state management and immutable data classes. To harness its capabilities, you must first set up your project correctly. This involves adding dependencies, installing plugins, and configuring the build runner for code generation. Let’s break this process down step by step.
Step 1: Add Dependencies
Begin by updating your `pubspec.yaml` file to include the necessary dependencies. Freezed relies on `freezed` and `freezed_annotation` for core functionality, while `build_runner` and `json_serializable` are essential for code generation and JSON serialization. Add the following lines under the `dev_dependencies` and `dependencies` sections:
Yaml
Dependencies:
Freezed_annotation: ^2.0.0
Dev_dependencies:
Build_runner: ^2.0.0
Freezed: ^2.0.0
Json_serializable: ^6.0.0
Run `flutter pub get` to fetch these packages. This step ensures your project has the foundational tools required for Freezed.
Step 2: Install Plugins
While Freezed itself doesn’t require additional plugins, integrating it with IDEs like Android Studio or VS Code enhances productivity. Install the Dart Code extension for VS Code or ensure the Dart plugin is enabled in Android Studio. These plugins provide syntax highlighting, code completion, and error checking for Freezed annotations, making development smoother. For VS Code, open the Extensions tab and search for "Dart Code" to install it.
Step 3: Configure Build Runner
The build runner is the engine behind Freezed’s code generation. To configure it, create a `build.yaml` file in the root of your project. This file specifies which builders to use and their settings. Add the following configuration:
Yaml
Targets:
$default:
Builders:
Freezed:
Options:
Make_collections_unmodifiable: false
Generate_for:
Lib/.dart
Json_serializable:
Options:
Explicit_to_json: true
Generate_for:
Lib/.dart
This setup ensures Freezed and JSON serialization are applied to all `.dart` files in the `lib` directory. Run `flutter pub run build_runner build` to generate the initial code. For automatic code generation during development, use `flutter pub run build_runner watch`.
Cautions and Practical Tips
While setting up Freezed, avoid common pitfalls like forgetting to run the build runner after making changes to annotated classes. This can lead to outdated or missing generated code. Additionally, ensure your IDE is configured to recognize Freezed annotations to avoid linting errors. If you encounter issues, verify that all dependencies are up to date and that the `build.yaml` file is correctly configured.
By following these steps, you’ll have a fully functional Freezed setup, ready to streamline your Flutter development with immutable data classes and efficient state management.
Freezing Beef Fat: A Guide to Preserving and Reusing It Later
You may want to see also
Explore related products
$11.99

Model Creation: Define immutable classes with `@freezed` and generate boilerplate code
Immutable classes are the backbone of robust Flutter applications, ensuring data consistency and predictability. With Freezed, defining these classes becomes a breeze. Start by annotating your class with `@freezed`, and Freezed will generate the necessary boilerplate code for you. This includes methods like `copyWith`, `==`, and `hashCode`, which are essential for immutable data handling. For instance, consider a simple `User` model:
Dart
Import 'package:freezed_annotation/freezed_annotation.dart';
Part 'user.freezed.dart';
@freezed
Class User with _$User {
Const factory User({
Required String name,
Required int age,
}) = _User;
}
Here, the `@freezed` annotation triggers code generation, and the `with _$User` mixin ensures the generated code is integrated seamlessly. The `const factory` keyword defines how instances of `User` are created, enforcing immutability from the start.
One of the standout features of Freezed is its ability to handle complex data structures with ease. For example, nested models or unions (classes that can represent multiple states) are simplified. Suppose you have a `Result` class that can be either `Success` or `Failure`:
Dart
@freezed
Class Result
Const factory Result.success(T data) = Success
Const factory Result.failure(String message) = Failure
}
This approach not only keeps your code clean but also makes it type-safe and easy to work with. Freezed’s pattern matching capabilities further enhance this by allowing you to handle different states elegantly:
Dart
Void handleResult(Result
Result.when(
Success: (data) => print('Data: $data'),
Failure: (message) => print('Error: $message'),
;
}
While Freezed simplifies model creation, it’s crucial to understand its limitations. For instance, Freezed doesn’t support nullable fields directly, so you’ll need to use `late` or optional parameters carefully. Additionally, ensure you run `flutter pub run build_runner build` after defining or modifying your models to generate the necessary code.
In conclusion, Freezed transforms the way you create immutable classes in Flutter, reducing boilerplate and increasing productivity. By leveraging its annotations and code generation, you can focus on building features rather than managing data structures. Whether you’re working on simple models or complex unions, Freezed provides a scalable and maintainable solution for your Flutter projects.
Steam Mop for Freezer Defrosting: Safe or Risky Method?
You may want to see also
Explore related products
$9.73

CopyWith Method: Use `copyWith` to create modified instances of freezed models
The `copyWith` method in Freezed is a powerful tool for creating immutable data models in Flutter. When working with freezed models, you often need to create a new instance with some fields modified while keeping the rest unchanged. Instead of manually constructing a new object, `copyWith` automates this process, ensuring type safety and reducing boilerplate code. For example, if you have a `User` model with fields like `name`, `age`, and `email`, you can easily create a new `User` instance with an updated `age` by calling `user.copyWith(age: 25)`. This method is particularly useful in state management, where you frequently update parts of your application state without mutating the original data.
To implement `copyWith`, ensure your freezed model is properly set up with the `@freezed` annotation and includes the `copyWith: true` option. For instance:
Dart
@freezed
Class User with _$User {
Const factory User({
Required String name,
Required int age,
Required String email,
}) = _User;
Factory User.fromJson(Map
}
Here, the `copyWith` method is automatically generated, allowing you to modify specific fields effortlessly. This approach not only keeps your code clean but also aligns with Flutter's reactive programming paradigm, where immutability is key to predictable state updates.
One common pitfall is overlooking the immutability aspect of freezed models. Since `copyWith` returns a new instance, ensure you update references accordingly. For example, if you’re using `Provider` or `Riverpod`, assign the new instance to the state object:
Dart
Final user = User(name: 'Alice', age: 30, email: '[email protected]');
Final updatedUser = user.copyWith(age: 31);
Ref.read(userProvider.notifier).state = updatedUser;
This ensures the UI reflects the updated state correctly. Additionally, `copyWith` is not limited to top-level fields; it works seamlessly with nested models. If your `User` model includes an `Address` object, you can update nested fields like so:
Dart
Final updatedUser = user.copyWith(address: address.copyWith(city: 'New York'));
In conclusion, the `copyWith` method is a cornerstone of working with freezed models in Flutter. It simplifies state updates, enforces immutability, and reduces the risk of errors associated with manual object creation. By leveraging `copyWith`, you can write cleaner, more maintainable code while adhering to Flutter's best practices for state management. Whether you're updating a single field or modifying nested objects, `copyWith` provides a concise and type-safe solution for managing immutable data models.
Freezing Salsa: A Handy Guide to Preserve Your Favorite Dip
You may want to see also
Explore related products

Union Types: Implement enums with `@Freezed` for handling multiple data states
In Flutter, managing multiple data states often leads to boilerplate code and complexity. Enter `@Freezed`, a code generation package that simplifies state management by leveraging union types. Union types, akin to enums but more powerful, allow you to represent multiple states within a single data structure. By combining `@Freezed` with union types, you can elegantly handle loading, success, error, and other states in a type-safe and concise manner. This approach not only reduces redundancy but also enhances readability and maintainability.
To implement union types with `@Freezed`, start by defining a sealed class that represents your data states. For instance, consider a `UserState` class with states like `Initial`, `Loading`, `Loaded`, and `Error`. Annotate this class with `@freezed` and specify the union types as subclasses. Each subclass can hold relevant data—`Loaded` might contain a `User` object, while `Error` could include an `Exception`. The `@Freezed` generator automatically creates boilerplate code for these states, including `when` and `maybeWhen` methods for pattern matching, ensuring you handle each state appropriately.
One of the standout benefits of this approach is its seamless integration with Flutter widgets. For example, you can use a `BlocBuilder` or `ValueListenableBuilder` to listen to changes in `UserState` and render UI based on the current state. If the state is `Loading`, show a progress indicator; if it’s `Loaded`, display user details; and if it’s `Error`, present an error message. This pattern eliminates the need for nested conditionals, making your code cleaner and more intuitive.
However, caution is warranted when dealing with deeply nested union types. While `@Freezed` handles complexity gracefully, overusing nested states can lead to convoluted logic. To mitigate this, keep your union types focused and avoid unnecessary nesting. Additionally, ensure proper testing of each state to verify correct behavior. Tools like `Freezed`’s built-in `map` and `maybeMap` methods can aid in writing robust tests by simplifying state transformations.
In conclusion, union types with `@Freezed` offer a robust solution for managing multiple data states in Flutter. By reducing boilerplate, improving type safety, and enhancing code readability, this approach empowers developers to build scalable and maintainable applications. Whether you’re handling API responses, form submissions, or complex workflows, `@Freezed`’s union types provide a flexible and efficient framework for state management.
Maximize Energy Savings: A Step-by-Step Guide to Using Freeze Miser
You may want to see also
Explore related products

Integration: Integrate freezed with providers, BLoC, or other state management solutions
Freezed, a powerful code generation tool for Dart, excels at creating immutable classes and simplifying state management in Flutter. Integrating it with existing state management solutions like Provider or BLoC unlocks a new level of efficiency and type safety in your Flutter applications.
Let's explore how.
Provider and Freezed: A Match Made in Flutter Heaven
Imagine a scenario where you have a complex UI displaying user data fetched from an API. Provider, with its change notifier pattern, is a natural fit for managing this state. Freezed steps in by generating immutable data models for your user data. This combination ensures that your UI reacts only to genuine data changes, preventing unnecessary rebuilds and improving performance. Think of Freezed as the meticulous librarian, ensuring your data remains pristine and unaltered, while Provider acts as the efficient messenger, delivering updates to the UI when needed.
For instance, define a `User` class using Freezed's `@freezed` annotation, guaranteeing immutability. Then, create a `UserProvider` that holds an instance of this `User` and notifies listeners upon changes. Your UI widgets can now listen to this provider, automatically updating when the user data changes, all while benefiting from Freezed's type safety and immutability guarantees.
BLoC and Freezed: Streamlining State Flows
BLoC's structured approach to state management, with separate streams for events and states, pairs beautifully with Freezed's immutable data models. Freezed-generated classes ensure that your BLoC states are immutable, preventing accidental mutations and making state changes predictable and traceable. This is crucial for debugging complex state flows.
Consider a todo list app. Define a `Todo` class with Freezed, ensuring each todo item is immutable. Your BLoC can then emit states like `TodoListLoaded` containing a list of these immutable `Todo` objects. This guarantees that the UI receives a snapshot of the todo list at a specific point in time, preventing inconsistencies caused by mutable data.
Beyond Provider and BLoC: Freezed's Universal Appeal
Freezed's integration isn't limited to Provider and BLoC. Its focus on immutability and type safety makes it a valuable asset for any state management solution. Whether you're using Riverpod, GetX, or even a custom solution, Freezed can enhance your codebase by:
- Enforcing immutability: Preventing unintended data modifications and ensuring predictable state changes.
- Improving type safety: Catching potential errors at compile time, leading to more robust code.
- Simplifying code: Generating boilerplate code for data classes, allowing you to focus on business logic.
Practical Tips for Integration
- Start small: Begin by integrating Freezed with a single feature or data model to familiarize yourself with the workflow.
- Leverage code generation: Utilize Freezed's code generation capabilities to minimize boilerplate and maintain clean code.
- Consider null safety: Freezed fully supports Dart's null safety features, ensuring type safety throughout your application.
- Explore community resources: The Flutter community has numerous tutorials and examples showcasing Freezed integration with various state management solutions.
By embracing Freezed's integration with Provider, BLoC, or other state management solutions, you'll unlock a new level of code quality, maintainability, and performance in your Flutter applications. Remember, immutability is not just a buzzword; it's a powerful tool for building robust and scalable Flutter apps.
Preserve Peaches Naturally: Sugar-Free Freezing Tips for Fresh Flavor
You may want to see also
Frequently asked questions
Freezed is a code generation package in Flutter that simplifies state management and immutable data modeling. It generates boilerplate code for immutable classes, copyWith methods, and value equality, reducing manual effort and minimizing errors. Use it to improve code readability, maintainability, and performance in your Flutter apps.
To set up Freezed, add `freezed` and `build_runner` as dependencies in your `pubspec.yaml` file. Then, run `flutter pub get` followed by `flutter pub run build_runner build` to generate the necessary code. Annotate your classes with `@freezed` and define the required fields and methods.
Define a class annotated with `@freezed` and specify the fields using the `factory` constructor. Freezed will automatically generate an immutable class with `copyWith`, `==`, and `hashCode` implementations. For example:
```dart
@freezed
class User with _$User {
const factory User({required String name, required int age}) = _User;
}
```
Yes, Freezed supports JSON serialization when combined with the `json_serializable` package. Add `@JsonSerializable()` to your class and generate the serialization code by running `flutter pub run build_runner build`. Use `toJson()` and `fromJson()` methods to convert between JSON and your immutable classes.
Freezed allows you to define unions using the `with` keyword and specifying multiple constructors. Each constructor represents a different state or type. For example:
```dart
@freezed
class Result with _$Result {
const factory Result.success(String data) = Success;
const factory Result.error(String message) = Error;
}
```
This enables pattern matching and type-safe handling of different cases.





























