Flutter: BLoC + Freezed — Write less code

We all know that using BLoC for state management is one of the best bets, but this comes with an ugly thing: You need to write a lot of code. In BLoC you need to write a base class for your state and your event and then create a lot of new classes for each new state or event. Here is where Freezed comes to play (Sealed/Union). Let’s compare it:

BLoC without Freezed vs with Freezed

❌ BLoC without Freezed

and now using freezed you will have a pretty small code and more readable compared to the previous one.

✅ With Freezed:

As you can notice it reduces a lot of code and makes it easy to understand, and one of the best benefits is that it is immutable!. You can also apply it to Cubit:

Using the power of freezed we can now emit new states that are more readable. That’s not all, you can also apply this to the UI layer side.

Freezed in the UI Layer Side

When we use BLoC Builder/Listener/Consumer we need to check the current state to draw the respective widget or to trigger an action. We can do this using different ways (like multiple if-then-else conditions) or we can go with freezed and get a different result.

BLoC Builder:

BLoC Listener:

Code Generation and Files Related

You can go using 2 approaches. Create 1 file for bloc, 1 for states and 1 for events, or create just one file for all.

If you do the first one you will notice that you will get:

  • 1 file for the bloc/cubit
  • 1 file for the state
  • 1 file for the events
  • 1 “generated file” for states
  • 1 “generated file” for events

These are a lot of files and probably you will create a directory to put all this together. But there’s the second way to get this done and just get 2 files for all.

To get this result you need to put the “states” and “events” in the same file where is the BLoC or Cubit located.

You will get 1 file for “bloc/cubit, state, events” and 1 file for all generated code. Caution: This approach will be the best bet for most of the cases, but sometimes it could introduce files with a lot of lines. You need to be wise and don’t create a file with 1k of lines that could be hard to read, always write your code thinking in your other team members and if your code is readable or not, also will be good to decide if as a team wants to follow this approach or keep things separated in multiple files.

As you can see freezed helps us to write more readable and flexible code. Give it try, and keep in mind that if you add it as a dependency you are not forced to update all your current BLoC files, you can migrate at your own pace.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Pablo Reyes

Pablo Reyes

Senior Android & Flutter Developer