What’s a Cubit?
It’s a class that stores an observable state, the observation is powered by Streams but in such a friendly way that it is not necessary to know reactive programming
Use super() to override the initial state.
How to connect a Cubit to the UI?
Use a Builder similar to StreamBuilder or FutureBuilder.
The difference is the possibility of rescuing a Cubit direct from Widget Tree by Providers.
At every state change — using the emit() as said before — , an updated widget is built.
If necessary only listen to the state changes without building a widget, use CubitListener. It’s useful to call side-effects based on the current state, like alerts and navigations.
It’s possible to control when to listen or to build(buildWhen and listenWhen).
BlocConsumer is a mix of builder and listener.
How to inject a Cubit in the Widget Tree?
Cubit uses the package provider for dependency injection, that’s familiar to most developers.
The level of accessibility of a Cubit is based on Provider depth.
Example: A cubit injected at MaterialApp it’s available throughout the App.
For more information, click here.
An application shows the weekly trending movies, these movies come from an external API.
Let’s solve it with Cubit.
1 — Representing the movies states:
Write an abstract class called MoviesState that extends Equatable.
Equatable is a package used to help the Cubit compare States, very useful to distinguish equal states with slightly different content.
There will be states for InitialList, Loading, Loaded Movies, and Error.
Equatable it’s just a tip.
2 — Construct a Cubit:
Is used a repository in this example but the choice of external data consult approach is free.
3 — Write the function that will emit the movies:
The function will be called directly in the constructor to load the movies at class instantiation.
The function can be called from a different place too.
4 — Connect Cubit to UI:
There will be a widget for every state, so it’s necessary to handle the type of each emitted state.
Complete example: https://github.com/irvine5k/cubit_movies_app/
The Cubit tests are similar to Stream or Bloc tests, so there’s no secret.
The difference of syntax between Cubit and Bloc
Cubit, it’s the perfect fit for simple states.
Cubit greatly reduced the complexity of using the Bloc package and its boilerplate.
Its strengths are simplicity, immutability, and interoperability with BLoC.
The Bloc will be built on top of Cubit in version 5, so you can use Cubit for simple states and as needed you can use the Bloc.
Want to contact me? My LinkedIN.