Member-only story
Cubit vs Bloc ⚔️
5 min readOct 13, 2024
Choosing the Right Tool for Efficient State Management in Your Flutter App 🛠️

Two powerful approaches for managing state in Flutter are Cubit and Bloc from the flutter_bloc
package. In this post, we'll break down the concepts of Cubit and Bloc, showing how to create and manage states, events, and event transformations.


Cubit (Counter Example)
import 'package:equatable/equatable.dart';
class CounterState extends Equatable {
final int counter;
const CounterState(this.counter);
factory CounterState.initial() => const CounterState(0);
CounterState copyWith({int? counter}) {
return CounterState(counter ?? this.counter);
}
@override
List<Object> get props => [counter];
@override
String toString() => 'CounterState(counter: $counter)';
}
- We use
Equatable
to handle equality checks. - The
copyWith
method allows updating the state without modifying the entire object. toString
provides a readable representation of the state.
import 'package:flutter_bloc/flutter_bloc.dart';
class CounterCubit extends Cubit<CounterState> {
CounterCubit() : super(CounterState.initial());
void increment() => emit(state.copyWith(counter: state.counter + 1));
void decrement() => emit(state.copyWith(counter: state.counter - 1));
}
- increment() and decrement() modify the state and emit new values.
- The
emit
function is used to update the state and notify the UI of changes.
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
void main() {
runApp(MaterialApp(home: CounterApp()));
}
class CounterApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (context) => CounterCubit(),
child: CounterView(),
);
}
}
class CounterView extends StatelessWidget {
@override
Widget build(BuildContext context) {…