Let’s go step by step — you’ll understand BLoC (Business Logic Component) state management in Flutter clearly and practically with a real example.
🧠 What is BLoC?
BLoC helps separate your UI (presentation) from your business logic.
It follows the principle:
UI sends events → BLoC processes them → emits new states → UI rebuilds.
So instead of writing logic inside your setState(), you handle logic inside the BLoC, and the UI just listens.
⚙️ Core Concepts
| Concept | Role | Example |
|---|---|---|
| Event | Represents what happened (user actions) | IncrementEvent, FetchUserEvent |
| State | Represents the UI condition | CounterInitial, CounterUpdated(5) |
| Bloc | Handles logic, maps Events → States | CounterBloc |
| BlocProvider | Makes a Bloc available to widgets | BlocProvider(create: (_) => CounterBloc()) |
| BlocBuilder | Rebuilds UI when state changes | Updates counter display automatically |
🧩 Example: Counter App using BLoC
Let’s build a simple counter app using flutter_bloc package.
🪜 Step 1: Add Dependency
In pubspec.yaml:
Run:
🪜 Step 2: Create the Event
counter_event.dart
🪜 Step 3: Create the State
counter_state.dart
🪜 Step 4: Create the BLoC
counter_bloc.dart
🪜 Step 5: Use it in the UI
main.dart
🧩 How It Works
-
User taps ➕ →
IncrementEventis added. -
The
CounterBlocreceives the event → increases count → emits newCounterState. -
BlocBuilderlistens → rebuilds the Text widget with new value.
✅ No setState() used — the UI updates automatically when the state changes.
📦 Folder Structure (Recommended)
⚡ Real-World Use Case Example
For example, in a Login screen:
-
Events →
LoginButtonPressed,LogoutPressed -
States →
LoginLoading,LoginSuccess,LoginFailure -
Bloc → Handles login API, emits new state
So, the same pattern scales well to API calls, form validation, and data management.
🔍 Summary
| Step | Description |
|---|---|
| 1 | Define Event (what happens) |
| 2 | Define State (UI data/status) |
| 3 | Create Bloc (handle logic) |
| 4 | Use BlocProvider in widget tree |
| 5 | Use BlocBuilder or BlocListener to rebuild or react to state |
Comments
Post a Comment