Event based Bloc
Block Pattern

Part 5 – Flutter BLoC Tutorial: Event-Based BLoC with Events, States & emit()

🧠 What is Event-Based BLoC?

Unlike Cubit, the BLoC pattern uses events to trigger state changes, making it ideal when:

  • ✅ You have multiple event types
  • ✅ You want to separate UI actions from business logic
  • ✅ You’re dealing with asynchronous or complex workflows

🎯 Let’s Build a Counter App with BLoC


🔹 Step 1: Define Events

📁 counter_event.dart


// All possible events for the Counter BLoC
abstract class CounterEvent {}

class IncrementEvent extends CounterEvent {}

class DecrementEvent extends CounterEvent {}

🔹 Step 2: Define States

📁 counter_state.dart


// State that holds the current count
abstract class CounterState {}

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

🔹 Step 3: 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(CounterValue(0)) {
    on<IncrementEvent>((event, emit) {
      final currentCount = (state as CounterValue).count;
      emit(CounterValue(currentCount + 1));
    });

    on<DecrementEvent>((event, emit) {
      final currentCount = (state as CounterValue).count;
      emit(CounterValue(currentCount - 1));
    });
  }
}

🧩 UI Integration

🔸 Provide the BLoC

📍 In your main widget tree:


BlocProvider(
  create: (context) => CounterBloc(),
  child: CounterPage(),
)

🔸 Show the State

📍 Inside the widget build method:


BlocBuilder<CounterBloc, CounterState>(
  builder: (context, state) {
    final count = (state as CounterValue).count;
    return Text('Count: \$count', style: TextStyle(fontSize: 30));
  },
)

🔸 Trigger Events

📍 Buttons to interact with BLoC:


FloatingActionButton(
  onPressed: () => context.read<CounterBloc>().add(IncrementEvent()),
  child: Icon(Icons.add),
),

FloatingActionButton(
  onPressed: () => context.read<CounterBloc>().add(DecrementEvent()),
  child: Icon(Icons.remove),
),

✅ Summary

Concept Description
Event What happened (e.g., Increment)
State The current UI/data state
on<Event>() Event handler in your BLoC
emit() Sends new state to the UI
BlocBuilder Rebuilds UI on state change
context.read().add() Triggers events from the UI

🚀 Coming Up Next:

Part 6 – BlocListener and BlocConsumer
Learn how to listen to BLoC changes (e.g., showing Snackbars or Alerts) and combine listeners + UI builders.

Leave a Reply

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