Sub topic 3
Your First Cubit: State, `emit`, and Methods
Assume you know Dart classes, generics, null safety, and async/await. You should also know the basics of Flutter widgets and setState. This chapter uses the flutter_bloc package.
What a Cubit does
A Cubit is a class that owns one piece of application state. It exposes the current value through state and changes that value by calling emit.
A Cubit does not receive named events. Instead, other code calls its public methods, such as increment() or loadTodos(). Each method decides when and how to publish a new state.
The state type is the type inside Cubit<T>. For a counter, the state can simply be an int.
import 'package:flutter_bloc/flutter_bloc.dart';
class CounterCubit extends Cubit<int> {
CounterCubit() : super(0);
void increment() {
emit(state + 1);
}
void decrement() {
emit(state - 1);
}
}
Future<void> main() async {
final cubit = CounterCubit();
final subscription = cubit.stream.listen(
(value) => print('New state: $value'),
);
cubit.increment();
cubit.increment();
cubit.decrement();
await Future<void>.delayed(Duration.zero);
await subscription.cancel();
await cubit.close();
}The constructor calls super(0), so the Cubit starts with the state 0. The state getter returns the current value. Calling emit changes the state and notifies listeners through the Cubit's stream.
The output is:
New state: 1
New state: 2
New state: 1The first state is available immediately from cubit.state, but the stream reports states emitted after a listener subscribes.
Keep state changes inside methods
A Cubit's methods are the boundary for changing its state. This keeps the rules for state changes in one place. A button does not calculate the next counter value itself. It calls increment(), and the Cubit performs the change.
For more complex features, the state type is usually a class instead of a primitive. A method can validate input, call a repository, or emit several states while work is in progress. For example, an asynchronous method might emit a loading state, await a repository call, and then emit success or failure. The next chapter models those states in detail.
A Cubit should also be closed when code creates it manually and no longer needs it. Flutter's BlocProvider normally manages this lifecycle for you.
The Cubit's state flow
A state transition should produce a new value rather than mutating the existing value. This makes changes easier to observe, test, and reason about.
Exercise
What state does a new CounterCubit have, and what state does it have after calling increment twice and decrement once?
Show answer
It starts at 0. After the calls, its state is 1.