Flutter: BLoC vs Cubit

Async* / Async / Sync

BLoC

  • We have two streams here: Events and States; and that means that all things that we can apply to a Stream we can do it here. Transformations.
  • We can do long duration operations here, things like: API calls, database, compressions or some other complex things.
  • If you send a lot of events for one BLoC could be difficult to track if you are not tracking them correctly.
  • Sometimes we want to receive this “state” synchronously, but with BLoC this is not possible.

Cubit

  • We can decide if we want to send these “states” in a synchronous or asynchronous way.
  • We still can do long duration operations here but using async not async* (stream), if you want to use a stream you need to implement more things or move up to BLoC.
  • We don’t have “Events” here, and these are helpful in different situations.
  • We don’t have streams, so no transformations.

Track Events and States

“BLoC is Event-Driven and Cubit not.”

¿When we should use Cubit?

  • When you want to send something synchronous.
  • When you don’t need to keep track of event-state transitions. You only want state tracking or track nothing (cubit is not event-driven).
  • You need do to something pretty simple. Like a custom toggle, a count-down timer, keep a state of a bar with multiple options. Keep in mind that if the things inside this cubit start become complex probably you should think of migrating it to BLoC (which shouldn’t be too difficult).

¿When we should use BLoC?

  • When you want to track event-state transitions. Helps for debugging, analytics, etc. For example, to know the order of how the events were sent.
  • When you send “Events” from different places. For example, you have multiple BLoC listeners and inside them you send multiple events to another BLoC.
  • You want to do some event transformation. Like buffer, throttle, debounceTime, etc. Think of all transformations that can be applied to a stream.

Additional Note

--

--

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