DEV Community

مصعب يوسف
مصعب يوسف

Posted on Originally published at ms3byoussef.medium.com

Generated Code in Flutter ”Freezed”

Improve Flutter Developer Skills ‘Freezed Package’

Generated Code in Flutter ”Freezed”

“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”

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.

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];
}
Enter fullscreen mode Exit fullscreen mode

“ 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”

Step 2: Create the Freezed Data Model

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

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;
}
Enter fullscreen mode Exit fullscreen mode

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:

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;
}
Enter fullscreen mode Exit fullscreen mode

in bloc

@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;
}
Enter fullscreen mode Exit fullscreen mode

Pattern Matching

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

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}');
    },
  );
}
Enter fullscreen mode Exit fullscreen mode

in bloc

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'),
  );
}
Enter fullscreen mode Exit fullscreen mode

CopyWith Method

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

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

final newClient = mainClient.copyWith(
email: lo@gmail.com,
phone: 010102211,
);
Enter fullscreen mode Exit fullscreen mode

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 on July 4, 2024.

Top comments (0)