Problem Statement
How do you implement a complete Bloc pattern using flutter_bloc? Explain events, states, and the Bloc class.
Explanation
Start by defining event classes representing user interactions or system events. Create a sealed class or abstract class for the base event, with concrete event classes extending it for different actions. For example, CounterEvent base with CounterIncremented and CounterDecremented events. Events are immutable and may contain data needed for processing.
Define state classes representing all possible states your UI can be in. Use a sealed class or abstract class for base state with concrete states like CounterInitial, CounterValue, CounterLoading, or CounterError extending it. States are immutable and contain data needed to render UI. Consider using packages like freezed for immutable data classes with copy methods and exhaustive pattern matching.
Create a Bloc class extending Bloc<Event, State>, implement event handlers using on<EventType>((event, emit) { ... }) to map events to states. Event handlers are asynchronous functions that process events and emit states using emit(newState). You can emit multiple states during processing, like emitting loading state, performing async work, then emitting success or error state.
Provide the Bloc using BlocProvider at appropriate level, use BlocBuilder to rebuild UI based on states, and use BlocListener for side effects. UI dispatches events to Bloc using context.read<CounterBloc>().add(CounterIncremented()). The Bloc processes events, emits states, and UI reacts. This separation makes business logic testable independently of UI, and the event-driven architecture provides clear audit trail of what happened.
