Learn/Advanced State Management/BLoC & Cubit

BLoC & Cubit

Manage state with the Business Logic Component (BLoC) pattern

8 min~6 min read+40 FX

You can read this lesson publicly. Sign in to unlock exercises, quiz, and FX progress tracking.

Table of Contents

  1. 1. Event And State Design
  2. 2. This Lesson In Simple Words
  3. 3. Your level focus
  4. 4. One practical habit
  5. 5. Deep Understanding Guide
  6. 6. Why this lesson matters
  7. 7. Study flow for better retention
  8. 8. Quick Glossary
  9. 9. Architecture Lens

Having trouble? AI is here to help

Ask context-aware questions about this lesson. Free plan: 5 questions/day. Upgrade to Premium for higher daily limits.

Use the AI button at the bottom of the screen

BLoC & Cubit

BLoC (Business Logic Component) is a state management pattern that strictly separates UI from business logic using events and states. The UI sends events to the BLoC, the BLoC processes them and emits new states, and the UI rebuilds based on the new state. This unidirectional data flow makes the app predictable and easy to test. Cubit is a lighter version of BLoC that uses direct method calls instead of event classes, reducing boilerplate while keeping the same architecture. The flutter_bloc package provides both BLoC and Cubit along with widgets like BlocBuilder, BlocListener, and BlocConsumer for connecting them to your UI.

dart
1// pubspec.yaml: flutter_bloc: ^8.1.3
2import 'package:flutter_bloc/flutter_bloc.dart';
3
4// ── CUBIT (simpler) ──
5class CounterCubit extends Cubit<int> {
6 CounterCubit() : super(0); // initial state = 0
7
8 void increment() => emit(state + 1);
9 void decrement() => emit(state - 1);
10 void reset() => emit(0);
11}
12
13// ── BLOC (event-driven) ──
14// Events
15abstract class CounterEvent {}
16class Increment extends CounterEvent {}
17class Decrement extends CounterEvent {}
18
19// Bloc
20class CounterBloc extends Bloc<CounterEvent, int> {
21 CounterBloc() : super(0) {
22 on<Increment>((event, emit) => emit(state + 1));
23 on<Decrement>((event, emit) => emit(state - 1));
24 }
25}
26
27// ── Provide to widget tree ──
28BlocProvider(
29 create: (context) => CounterCubit(),
30 child: const CounterPage(),
31)
32
33// ── Use in widgets ──
34class CounterPage extends StatelessWidget {
35 @override
36 Widget build(BuildContext context) {
37 return Scaffold(
38 body: Center(
39 child: BlocBuilder<CounterCubit, int>(
40 builder: (context, count) => Text('Count: $count'),
41 ),
42 ),
43 floatingActionButton: FloatingActionButton(
44 onPressed: () => context.read<CounterCubit>().increment(),
45 child: const Icon(Icons.add),
46 ),
47 );
48 }
49}

Cubit vs BLoC

💡 Cubit vs BLoC

Use Cubit for simple use cases like counters, toggles, and forms where you call methods directly. Use BLoC when you need event-driven architecture with event transformations, debouncing, throttling, or complex async flows that benefit from explicit event classes.

Event And State Design

BLoC quality depends on event and state design clarity:

  • Events should represent user intent (SearchSubmitted, RetryPressed), not low-level UI actions.
  • States should be explicit and finite (initial, loading, success, failure).
  • Keep state immutable and derive UI from state only.
  • Use event transformers for debounce, throttle, or restartable async tasks.

When event semantics are clear, debugging and testing become far easier across teams.

BLoC Pitfalls

  • Emitting many loosely defined states with overlapping meaning.
  • Triggering navigation directly inside build methods instead of listeners.
  • Running long async work in UI callbacks instead of bloc handlers.
  • Forgetting to cancel subscriptions in blocs managing streams.
  • Using BLoC for tiny local widget state that should stay in setState.

BLoC Quality Checklist

  • Every public event has deterministic state transitions with tests.
  • Error states include user-safe messaging and retry actions.
  • BlocListener or BlocConsumer handles side effects cleanly.
  • Async concurrency is controlled with suitable event transformers.
  • Bloc and repository boundaries are documented and easy to follow.

This Lesson In Simple Words

Manage state with the Business Logic Component (BLoC) pattern. State is data that changes over time and controls what users see on the screen.

Your level focus

Think in architecture, reliability, and team-level maintainability.

One practical habit

Keep state as close as possible to where it is used, then lift it only when sharing is required.

Deep Understanding Guide

Why this lesson matters

State management is the difference between predictable apps and hard-to-debug UI behavior.

Study flow for better retention

  1. Separate UI, state, and data boundaries before writing implementation details.
  2. Trace one user action from button tap to state update to rebuilt UI.
  3. If another developer can read your flow quickly, your design choices are clear.

Common Mistakes To Avoid

  • Calling setState high in the tree when only a small part needs refresh.
  • Keeping duplicated state in multiple widgets without a single source of truth.
  • Mutating collections directly and expecting UI updates automatically.
  • Choosing a heavy state library before understanding simple local state.

Practice Sprint (15-25 Minutes)

  • Before running sample code, predict output and behavior in one sentence.
  • Build one feature with local setState, then refactor it to Provider or Riverpod.
  • Create loading, success, and error states for one async user flow.
  • Write a small state diagram for a login form and implement it.
  • Complete the required exercises without using hints on the first attempt.
  • Answer this question out loud before checking quiz options: "What is the key difference between Cubit and BLoC?".

Quick Glossary

  • widget: A reusable UI building block in Flutter.
  • state: Data that can change and update what the user sees.
  • build: The method that describes UI for the current state.
  • bloc: An event-to-state pattern that separates logic from UI.
  • async: Code that runs over time without blocking the UI thread.

Code Comprehension Drill

  • State the purpose of the code block in one line before reading details.
  • Mark inputs, state changes, and final output.
  • Change one small value and predict what should happen before running.
  • Run again and compare your prediction with actual behavior.

Architecture Lens

State boundaries define module boundaries, so clear ownership prevents future regressions.

As your app grows, keep UI, state, and data responsibilities separate so each part stays testable and easier to modify.

Lesson Completion Checklist

  • I can explain "BLoC & Cubit" in simple words without reading notes.
  • I can describe one real app situation where this concept is required.
  • I know at least one mistake to avoid: Calling setState high in the tree when only a small part needs refresh.
  • I can modify one code sample and correctly predict the behavior change.
  • I can finish required exercises with understanding, not trial-and-error guesses.

Frequently Asked Questions

What is the key difference between Cubit and BLoC?

BLoC receives Events and produces States. Cubit calls methods directly. Cubit is simpler for most cases.

How do you emit a new state from a Cubit?

emit() is used in both Cubit and BLoC to output a new state to listeners.

Which widget provides a BLoC/Cubit to the widget tree?

BlocProvider creates and provides a BLoC/Cubit to its child widget subtree.

Suggest Improvement

Something seems incorrect, unclear, or missing? Let us know.

About The Author

FlutterCraft editorial lessons are reviewed by experienced Flutter developers and updated to stay aligned with modern Flutter and Dart best practices.

Reference docs: Flutter Documentation, Dart Language Tour, and official package documentation where relevant.

Sign in to continue with exercises and quiz for this lesson.

Sign In to Continue