Skip to main content

BLoC (Business Logic Component) state management in Flutter

 

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

ConceptRoleExample
EventRepresents what happened (user actions)IncrementEvent, FetchUserEvent
StateRepresents the UI conditionCounterInitial, CounterUpdated(5)
BlocHandles logic, maps Events → StatesCounterBloc
BlocProviderMakes a Bloc available to widgetsBlocProvider(create: (_) => CounterBloc())
BlocBuilderRebuilds UI when state changesUpdates 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:

dependencies: flutter: sdk: flutter flutter_bloc: ^8.1.3

Run:

flutter pub get

🪜 Step 2: Create the Event

counter_event.dart

abstract class CounterEvent {} class IncrementEvent extends CounterEvent {} class DecrementEvent extends CounterEvent {}

🪜 Step 3: Create the State

counter_state.dart

class CounterState { final int count; CounterState(this.count); }

🪜 Step 4: Create the BLoC

counter_bloc.dart

import 'package:flutter_bloc/flutter_bloc.dart'; import 'counter_event.dart'; import 'counter_state.dart'; class CounterBloc extends Bloc<CounterEvent, CounterState> { CounterBloc() : super(CounterState(0)) { on<IncrementEvent>((event, emit) { emit(CounterState(state.count + 1)); }); on<DecrementEvent>((event, emit) { emit(CounterState(state.count - 1)); }); } }

🪜 Step 5: Use it in the UI

main.dart

import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'counter_bloc.dart'; import 'counter_event.dart'; import 'counter_state.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: BlocProvider( create: (_) => CounterBloc(), child: CounterScreen(), ), ); } } class CounterScreen extends StatelessWidget { @override Widget build(BuildContext context) { final counterBloc = context.read<CounterBloc>(); return Scaffold( appBar: AppBar(title: const Text('BLoC Counter')), body: Center( child: BlocBuilder<CounterBloc, CounterState>( builder: (context, state) { return Text( 'Count: ${state.count}', style: const TextStyle(fontSize: 30), ); }, ), ), floatingActionButton: Row( mainAxisAlignment: MainAxisAlignment.end, children: [ FloatingActionButton( heroTag: 'increment', onPressed: () => counterBloc.add(IncrementEvent()), child: const Icon(Icons.add), ), const SizedBox(width: 10), FloatingActionButton( heroTag: 'decrement', onPressed: () => counterBloc.add(DecrementEvent()), child: const Icon(Icons.remove), ), ], ), ); } }

🧩 How It Works

  1. User taps ➕ → IncrementEvent is added.

  2. The CounterBloc receives the event → increases count → emits new CounterState.

  3. BlocBuilder listens → rebuilds the Text widget with new value.

No setState() used — the UI updates automatically when the state changes.


📦 Folder Structure (Recommended)

lib/ │ ├── bloc/ │ ├── counter_bloc.dart │ ├── counter_event.dart │ └── counter_state.dart │ └── ui/ └── counter_screen.dart

⚡ 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

StepDescription
1Define Event (what happens)
2Define State (UI data/status)
3Create Bloc (handle logic)
4Use BlocProvider in widget tree
5Use BlocBuilder or BlocListener to rebuild or react to state

Comments

Popular posts from this blog

How to write a code of Encode and Decode json data in Dart language

 Encode and decode JSON data in dart language import 'dart:convert'; void main() {   // Original data as a Dart map   Map<String, dynamic> originalData = {     'field1': 'value1',     'field2': 42,     'field3': true,   };   // Encode the Dart map to JSON string   String jsonString = jsonEncode(originalData);   print('Original JSON String:');   print(jsonString);   // Encode the JSON string to base64   String base64EncodedString = base64.encode(utf8.encode(jsonString));   print('\nBase64 Encoded String:');   print(base64EncodedString);   // Decode the base64 string to JSON string   String decodedJsonString = utf8.decode(base64.decode(base64EncodedString));   print('\nDecoded JSON String:');   print(decodedJsonString);   // Decode the JSON string to a Dart map   Map<String, dynamic> decodedData = jsonDecode(decodedJsonString);   print('\nDecoded Dart Ma...

About of Free Learning Tech Point

  Welcome to Free Learning Tech Point , where knowledge meets accessibility. Our platform is dedicated to providing high-quality educational resources and e-learning opportunities to learners around the world, completely free of charge. Our Mission: At Free Learning Tech Point, we believe that education is a fundamental right, and everyone should have access to valuable learning materials. Our mission is to break down barriers to education by offering a diverse range of courses, tutorials, and resources across various subjects and disciplines. What Sets Us Apart: - Free Access: Our commitment is to make learning accessible to all. No subscription fees, no hidden costs – just free, open access to knowledge.    - Quality Content: We curate and create content that is both engaging and informative. Whether you're a student, professional, or lifelong learner, our resources are designed to cater to various learning styles and levels. - Diverse Subjects: From tech and science...

Privacy Policy Of Free Learning Tech Point

  Thank you for visiting Free Learning Tech Point . You can use our website, services, and products with the awareness that this Privacy Policy describes how we gather, use, disclose, and protect your personal information. 1- Information We Collect: We may collect personal information that you provide directly to us, such as your name, email address, and any other information you choose to provide when using our Services. We may also collect non-personal information, such as aggregated data and usage patterns. 2- How We Use Your Information: We may use the information we collect for various purposes, including but not limited to: Providing and improving our Services. Responding to your inquiries and requests. Analyzing usage patterns and trends. Sending you updates, newsletters, and other communications. Personalizing your experience on our platform. 3- Cookies and Similar Technologies: We may use cookies and similar technologies to collect information about your interactions with...