📘 2. Getting Started with Flutter BLoC

📘 2. Getting Started with Flutter BLoC

AI Reading

Quick summary of this article

The BLoC pattern is a state management architecture for Flutter that separates business logic from the UI using streams. It works by having the UI send events to the BLoC, which processes them and emits states that the UI listens to and rebuilds from. Cubit is a simpler version of BLoC that emits states directly without requiring event classes, making it suitable for most use cases.

  • BLoC uses streams (output) and sinks (input) to manage data flow, with data pushed via sink.add() and listened to via stream.listen().
  • Cubit is easier to learn and requires less boilerplate than full BLoC, but BLoC offers more flexibility for complex user flows that depend on many event types.
  • To get started, add flutter_bloc: ^8.1.3 and bloc: ^8.1.2 to your pubspec.yaml and run flutter pub get.
  • A basic Cubit example creates a class extending Cubit<int> with an initial state of 0 and an increment() method that emits state + 1.
  • In the UI, use BlocProvider to supply the Cubit and BlocBuilder to listen for state changes and rebuild the widget tree accordingly.

🔍 What is the BLoC Pattern?

The BLoC (Business Logic Component) pattern is a state management architecture designed to separate your application’s business logic from the UI layer. It helps you build scalable, maintainable, and testable Flutter apps using Streams.

🔄 How it Works:

  • The UI sends Events to the BLoC.
  • The BLoC processes those events and emits States.
  • The UI listens to those states and rebuilds accordingly.

This pattern allows you to manage complex UI flows with multiple states in a predictable way.


🔁 How BLoC Works (Streams & Sinks)

At the core of the BLoC pattern are:

  • Streams – the output, or data you want to listen to.
  • Sinks – the input, or data you want to add into the system.

✅ Simple Stream Example:


final _controller = StreamController();
Stream get stream => _controller.stream;
Sink get sink => _controller.sink;

void increment(int value) {
  sink.add(value + 1);
}
  
  • You push data using the sink.add() method.
  • You listen to data using the stream.listen() method.

In actual Flutter BLoC, the BLoC or Cubit class internally manages this mechanism.


🔄 BLoC vs Cubit

Feature Cubit BLoC
Event class ❌ Not required ✅ Required
Simplicity ✅ Easier to learn ⚠️ More boilerplate
Use case Simple & moderate logic Complex user flows
State changes Direct (emit()) Via events & event handlers
Flexibility Limited Highly flexible

📝 Cubits are a simpler form of BLoCs — great for most use-cases unless your logic depends on many types of events.


🛠 Installing flutter_bloc and bloc Packages

To get started, you need to install the required dependencies:

1️⃣ Add to pubspec.yaml:


dependencies:
  flutter_bloc: ^8.1.3
  bloc: ^8.1.2
  

Make sure to check for the latest versions on pub.dev.

2️⃣ Run:

flutter pub get

✅ Simple Cubit Example

Let’s build a basic counter using Cubit.

📁 counter_cubit.dart


import 'package:flutter_bloc/flutter_bloc.dart';

class CounterCubit extends Cubit {
  CounterCubit() : super(0);

  void increment() => emit(state + 1);
}
  

🧩 Usage in UI:


BlocProvider(
  create: (_) => CounterCubit(),
  child: BlocBuilder<CounterCubit, int>(
    builder: (context, count) {
      return Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text('Count: \$count', style: TextStyle(fontSize: 24)),
          ElevatedButton(
            onPressed: () => context.read().increment(),
            child: Text('Increment'),
          ),
        ],
      );
    },
  ),
);
  

✅ What Happens Here:

  • CounterCubit starts with an initial state of 0.
  • When the button is tapped, it calls increment(), which emits state + 1.
  • BlocBuilder listens to state changes and rebuilds the Text widget with the new count.

🚀 Next Up:

Creating Events and States in BLoC — Learn how to build a full BLoC (not just Cubit) using events and states.

Leave a Reply

Your email address will not be published. Required fields are marked *