The main difference between Bloc and Cubit, is that the Bloc requires the implementation of events (Events) who will be responsible for changing their states (States). A Cubit is a lighter version of the Bloc, as it only works with states and internal methods that will directly alter these states.
In Widgets that consume a Bloc, for example the Blocbuilder, you can exchange a Bloc for a Cubit with ease, since the Bloc is built internally through a Cubit and these Widgets observe only the state of the object.
The advantage of using a Cubit is that for simpler use cases, you have the facility to not need to declare different events and mainly to map these events to the internal states of the object, which improves readability and reduces the amount of code to perform the task.
Simple Bloc example implementing a counter:
/// Evento a ser processado por [CounterBloc].
enum CounterEvent {
/// Notifica o Bloc a incrementar seu estado.
increment,
/// Notifica o Bloc a fazer um decremento em seu estado.
decrement
}
class CounterBloc extends Bloc<CounterEvent, int> {
CounterBloc() : super(0);
//Método que mapeia Eventos adicionados ao Bloc para novos Estados
@override
Stream<int> mapEventToState(CounterEvent event) async* {
switch (event) {
case CounterEvent.decrement:
yield state - 1;
break;
case CounterEvent.increment:
yield state + 1;
break;
default:
addError(Exception('unsupported event'));
}
}
}
Cubit that implements the same behavior without the need to declare and map events to states:
class CounterCubit extends Cubit<int> {
CounterCubit() : super(0);
void increment() => emit(state + 1);
void decrement() => emit(state - 1);
}
Good answer, you say:
"você pode trocar trocar um BLoC por um Cubit com facilidade"
hints that if I have code with Bloc (and if I want to simplify with Cubit) I can implement Cubit easily, is that really it? Could exemplify in the answer?– rubStackOverflow
Thanks rubStackOverflow, updated the reply to demonstrate the idea.
– Tiago Loureiro