DEV Community

Cover image for Chapter 3: What Are Bloc Events and States?
Md. Al-Amin
Md. Al-Amin

Posted on

Chapter 3: What Are Bloc Events and States?

Hi there! I’m so glad to see you here again. By now, you’re already familiar with the basics of Bloc and how Equatable simplifies state management. But today, we’re stepping into the core of Bloc state management—events and states.

Let me tell you a little story to help you understand. Imagine you’re running a coffee shop. Customers (users) walk in and place orders (events). You, as the barista, prepare the coffee and serve it (process the events). The happy customer enjoying their latte? That’s the state!

In the same way, Bloc helps your app respond to user actions (events) and update what the user sees (states). Sounds fun, right? Let’s dive in and learn together, step by step.

What Are Events and States?

Let’s break it down simply:

  • Events: These are signals that something happened in the app. For example, when someone presses a button, that’s an event.
  • States: These represent how your app looks or behaves at a specific moment. For example, the text on the screen or a loading spinner is the state.

Here’s a quick analogy:

  • Event: You order a pizza.
  • State: You receive the pizza.

In between these steps, someone (Bloc) takes your order, prepares the pizza, and delivers it. Bloc acts as the bridge between what happens (event) and what changes (state).

Why Should You Care?

Think of your app as a conversation:

  • You Speak: You (the user) press a button or perform an action (event).
  • Your App Responds: The app processes the action and updates what you see (state).

Without this structure, your app might behave unpredictably. Bloc keeps this flow organized, so your app is smooth, reliable, and easy to manage.

Let’s Build Something Cool: A Counter App

Enough theory! Let’s create a small app to see Bloc, events, and states in action. Ready?

We’ll make an app where:

  • A number on the screen updates as you press buttons.
  • You can increase, decrease, or reset the number.

Step 1: Get Started

First, make sure you’ve added the flutter_bloc package to your project. Add this to your pubspec.yaml:

dependencies:
  flutter_bloc: ^8.0.0
Enter fullscreen mode Exit fullscreen mode

Run flutter pub get to install it.

Step 2: Define the Events

Imagine you’re building a counter app. What actions can the user perform?

  • Increase the number.
  • Decrease the number.
  • Reset the number.

These actions are your events. Let’s define them:

abstract class CounterEvent {}  

class Increment extends CounterEvent {}  
class Decrement extends CounterEvent {}  
class Reset extends CounterEvent {}  
Enter fullscreen mode Exit fullscreen mode

Step 3: Define the States

Now, think about what your app will show based on those events. For the counter app, the state is just the number displayed on the screen.

class CounterState {  
  final int counterValue;  

  CounterState({required this.counterValue});  
}  
Enter fullscreen mode Exit fullscreen mode

Step 4: Create the Bloc

This is the part where magic happens! The Bloc listens to events, decides what to do, and updates the state.

import 'package:flutter_bloc/flutter_bloc.dart';  

class CounterBloc extends Bloc<CounterEvent, CounterState> {  
  CounterBloc() : super(CounterState(counterValue: 0)) {  
    on<Increment>((event, emit) {  
      emit(CounterState(counterValue: state.counterValue + 1));  
    });  

    on<Decrement>((event, emit) {  
      emit(CounterState(counterValue: state.counterValue - 1));  
    });  

    on<Reset>((event, emit) {  
      emit(CounterState(counterValue: 0));  
    });  
  }  
}  
Enter fullscreen mode Exit fullscreen mode

Let me explain:

The Bloc starts with an initial state: counterValue: 0.
When an Increment event occurs, the counter increases by 1.
When a Decrement event occurs, the counter decreases by 1.
When a Reset event occurs, the counter goes back to 0.

Step 5: Build the App

Now, let’s connect the Bloc to a simple Flutter UI:

import 'package:flutter/material.dart';  
import 'package:flutter_bloc/flutter_bloc.dart';  

class CounterApp extends StatelessWidget {  
  @override  
  Widget build(BuildContext context) {  
    return BlocProvider(  
      create: (_) => CounterBloc(),  
      child: MaterialApp(home: CounterScreen()),  
    );  
  }  
}  

class CounterScreen extends StatelessWidget {  
  @override  
  Widget build(BuildContext context) {  
    final counterBloc = BlocProvider.of<CounterBloc>(context);  

    return Scaffold(  
      appBar: AppBar(title: Text('Counter App')),  
      body: BlocBuilder<CounterBloc, CounterState>(  
        builder: (context, state) {  
          return Center(  
            child: Text(  
              'Counter Value: ${state.counterValue}',  
              style: TextStyle(fontSize: 24),  
            ),  
          );  
        },  
      ),  
      floatingActionButton: Row(  
        mainAxisAlignment: MainAxisAlignment.end,  
        children: [  
          FloatingActionButton(  
            onPressed: () => counterBloc.add(Increment()),  
            child: Icon(Icons.add),  
          ),  
          SizedBox(width: 10),  
          FloatingActionButton(  
            onPressed: () => counterBloc.add(Decrement()),  
            child: Icon(Icons.remove),  
          ),  
          SizedBox(width: 10),  
          FloatingActionButton(  
            onPressed: () => counterBloc.add(Reset()),  
            child: Icon(Icons.refresh),  
          ),  
        ],  
      ),  
    );  
  }  
}  

void main() => runApp(CounterApp());  
Enter fullscreen mode Exit fullscreen mode

It’s Your Turn!

Now it’s time for you to try:

  • Change the Colors: Make the buttons or text change color when the number is positive or negative.
  • Add a Message: Show a "Great job!" message when the counter reaches 10.
  • Experiment: Add a new event to double the counter value.

What Did We Learn Today?

  • Events are actions triggered by the user (e.g., button clicks).
  • States are the results of those actions (e.g., updated number).
  • Bloc connects them, making your app more organized and easier to manage.

What’s Next?

In the next chapter, we’ll explore how to manage more complex events and states, including tips for larger apps. For now, go ahead and try the tasks I shared above. Share your results—I’d love to see what you come up with!

See you soon in the next chapter! 😊

Top comments (0)