Flutter Bloc Library: When You Should Use It

Mario Gunawan
Flutter Tips
Published in
3 min readOct 14, 2022

A lot of people have been using Bloc without understanding when they should use it. In this article I will explain in which use cases are blog useful, and in which it is not.

What is Bloc?

Bloc is an acronym for “Business LOgic Component.” Bloc tries to separate the logic (usually state) from the UI component (the widget). The widget that uses Bloc will be able to remain stateless and remains responsive to state changes.

The Good

Of course, since Bloc makes us able to separate logic and UI in our components, we are able to make changes easier. Consider this scenario: You found a bug in your application that is related to the state of the app. Without bloc, you need to skim through your component tree to find out which component is causing an issue. Blergh. It will be a time-consuming task just to find the problem-causing state within those UI! But with bloc, we only need to change the causing bloc state. Voila! And speaking about conveniences while developing, do you often pass states / callbacks to child widgets?

Passing state or callbacks to a child widget is a common issue. If there is a widget that needs to know the state of its parent, but the parent is four layer above, usually we needs to pass down all the functions down, even to the widgets that doesn’t needs it.

Usual Approach

Using bloc, The we doesn’t need to pass down all the needed states, and you only need to pass the event

Using Bloc, no state / callback passed down

If you came from react, you probably noticed that this pattern is similar to React’s UseContext, and yes, it is a pretty similar concept.

To summarize the benefits:

  • Better Separation of concerns
  • Simpler Passing of State through Context

When To Not Use It

Other than more boilerplate codes, you should not use Bloc when the state is tightly coupled with the UI. For example, if you have a component that manages animation by manipulating the the child’s bounding rectangle, you should not use use Bloc. Because you need to have the access to UI to get the state, it doesn’t make sense to separate it from the UI itself. This also applies to keys, controllers, and other UI-related state.

Conclusion

Should you use bloc? If your application contains some states, some of it being passed around, then yes. But if your application doesn’t have a lot of states, then it’s fine to not use it.

Further reading material:

--

--

Mario Gunawan
Flutter Tips

I'm a mobile / web developer. I'm mostly writing articles about software development.