# Generated Code in Flutter ”Freezed”

## Improve Flutter Developer Skills ‘**Freezed** Package’

![Generated Code in Flutter ”Freezed”](https://miro.medium.com/v2/resize:fit:700/1*71IBKp0IVtNoDkC0wv3KHg.gif)
> “Peace be upon you “  
> We all know that everyone wants to reach the maximum stages of development in work and science, This is no different when you work in the field of mobile application development, Especially with Google developers who have developed flutter the most amazing framework which contains many useful libraries, one of which we will talk about: `freezed`

> ***Why we need Freezed ?***

*Dart is awesome, but defining a “model” can be tedious. You have to:*

- define a constructor + properties
- override `toString`, `operator ==`, `hashCode`
- implement a `copyWith` method to clone the object
- handle (de)serialization

Implementing all of this can take hundreds of lines, which are error-prone and affect the readability of your model significantly.

Freezed tries to fix that by implementing most of this for you, allowing you to focus on the definition of your model.

## Key Features of the `freezed` Package

1. **Immutable Models:** With `freezed`, the generated models are immutable by default. This prevents unintended changes to data and enhances predictability in your application's behavior.
2. **Union Types**: `freezed` allows you to define union types, which represent a value that could be one of several possible types. This is particularly useful for scenarios like representing different states of an entity.
3. **Pattern Matching:** The package provides a powerful pattern matching mechanism, similar to pattern matching in functional programming languages. This helps in handling different cases of union types with ease.
4. **CopyWith Method:** `freezed` generates a `copyWith` method for each model, enabling you to create modified copies of objects without modifying the original object itself.
5. **As same As Equatable:** The generated models implement the `Equatable` interface, making it easy to compare instances for equality.

**if you don’t know the “Equatable Package”**

![Generated Code in Flutter ”Freezed”](https://miro.medium.com/v2/resize:fit:700/1*XOBBerR7ir3nh7GWpVJcWw.png)

***Equatable*** is a library that helps implement value equality in Dart classes by overriding the == operator and ***hashCode*** method. It simplifies the process of comparing objects based on their properties.

To use ***Equatable***, you need to extend the ***Equatable*** class and override the props method, which returns a list of properties to be used for comparison. The == operator and ***hashCode*** method are automatically generated based on the properties specified in props.

```plaintext
import 'package:equatable/equatable.dart';

class Person extends Equatable {
  final String name;
  final int age;

  Person(this.name, this.age);

  @override
  List<Object?> get props => [name, age];
}
```

## ***“ Freezed Package “***

is a code generation library that provides a concise way to create immutable value classes with value equality, pattern matching, Union Types**,** and copy methods. It generates boilerplate code for you based on the class definition.

To use ***Freezed***, you need to annotate your class with @freezed and specify the constructors and properties. ***Freezed*** then generates code for value equality, pattern matching, and copy methods automatically.

How To Use?

## Step 1: Add Dependencies

To use Freezed in your Flutter project, you need to add the following dependencies to your pubspec.yaml file:

![Generated Code in Flutter ”Freezed”](https://miro.medium.com/v2/resize:fit:700/1*TZC6DbYvdZowHs7y4F3hEg.png)

## Step 2: Create the Freezed Data Model

Define your immutable data model using Freezed. For example, let’s create a simple `User` model:

```plaintext
import 'package:flutter/foundation.dart';
import 'package:freezed_annotation/freezed_annotation.dart';

part 'user.freezed.dart';
@freezed
abstract class User with _$User {
  const factory User({
    String? name,
    String? email,
  }) = _User;
}
```

## Using Union Types

Imagine a scenario where a `Person` can be either a `Student` or a `Teacher`. We can use union types to represent this:

```plaintext
freezed
abstract class User with _$User{
  const factory User.Client({
    String? name,
    String? email,
    String? phone
  }) = Client;

const factory User.Employee({
    String? name,
    String? email,
    UserRole? role;
  }) = Employee;
}
```

> **in bloc**

```plaintext
@freezed
abstract class AppState with _$AppState {
  const factory AppState.initial() = _Initial;
  const factory AppState.loading() = _Loading;
  const factory AppState.loaded(List<User> users) = _Loaded;
  const factory AppState.error(String message) = _Error;
}
```

## Pattern Matching

Pattern matching allows you to handle different cases of union types succinctly:

```plaintext
void printUserInfo(Useruser) {
  user.when(
    clien: (name, age, grade) {
      print('Name: $name, Email: $age, Phone: $phone');
    },
    employee: (name, age, subject) {
      print('Name: $name, Email: $age, Role: ${role.toString}');
    },
  );
}
```

> **in bloc**

```plaintext
void handleAppState(AppState state) {
  state.when(
    initial: () => print('Initial state'),
    loading: () => print('Loading state'),
    loaded: (users) => print('Loaded state with ${users.length} users'),
    error: (message) => print('Error state: $message'),
  );
}
```

## CopyWith Method

The `copyWith` method enables you to create modified copies of objects:

```plaintext
final mainClient= Person.student(
name: 'Alice',
 email: mo@gmail.com,
 phone: 010101111,
);

final newClient = mainClient.copyWith(
email: lo@gmail.com,
phone: 010102211,
);
```

> Goodbye to another Package and the How to Develop Yourself series

## Conclusion

The `freezed` package is a powerful tool,Freezed greatly reduces the amount of code that programmers have to creating immutable data models, union types, and pattern matching in Flutter applications. This results in cleaner and easier to understand code. By generating necessary code, it reduces boilerplate, Code generated by Freezed provides type safety, which reduces the chance of runtime errors related to state changes.  
Improved developer productivity.  
With less manual coding and automatic creation of necessary methods, programmers can focus more on application logic and features and improve overall efficiency.

## References

<https://resocoder.com/2020/02/11/freezed-data-class-union-in-one-dart-package/>

<https://pub.dev/packages/freezed#how-to-use>

<https://pub.dev/packages/equatable>

<https://www.youtube.com/watch?v=tu95Gjl6wS4>

<https://medium.com/@samra.sajjad0001/exploring-the-purpose-and-use-of-the-freezed-package-in-flutter-baec8d52a99f>

---
Originally published on [Medium](https://ms3byoussef.medium.com/improve-flutter-developer-skills-freezed-package-e0cace053712) on July 4, 2024.
