Lädt...

🔧 Chapter 3: What Are Bloc Events and States?


Nachrichtenbereich: 🔧 Programmierung
🔗 Quelle: dev.to

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

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 {}  

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});  
}  

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));  
    });  
  }  
}  

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());  

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! 😊

...

🔧 Chapter 3: What Are Bloc Events and States?


📈 59.35 Punkte
🔧 Programmierung

🔧 Testing Dependent Events in Flutter Bloc: Seeding State &amp; Handling Multiple Events


📈 42.48 Punkte
🔧 Programmierung

🔧 Chapter 4: Installing Bloc Plugin in VS Code &amp; Android Studio


📈 36.29 Punkte
🔧 Programmierung

🔧 Chapter 2: Mastering Equality with the Equatable Package in Flutter Bloc


📈 36.29 Punkte
🔧 Programmierung

🔧 Flutter Bloc State Management Roadmap: Chapter 1 — Roadmap to Mastery


📈 36.29 Punkte
🔧 Programmierung

🔧 Flutter Bloc Transformer Events


📈 32.68 Punkte
🔧 Programmierung

📰 Fortnite: Wann ist Ende von Chapter 3 und Start von Chapter 4? Datum bekannt


📈 26.83 Punkte
📰 IT Nachrichten

🔧 Clean Code Architecture and BLoC in Flutter: A Comprehensive Guide for Beginners and Experts


📈 25.6 Punkte
🔧 Programmierung

🔧 🧠 State Management in Flutter: Choosing Between Bloc, Riverpod, and Provider


📈 24.24 Punkte
🔧 Programmierung

🎥 🔥 Firebase, 🧊 Bloc, and 🔊 just_audio


📈 24.24 Punkte
🎥 Video | Youtube

🔧 Flutter app, fading chat logic with bloc and hooks


📈 24.24 Punkte
🔧 Programmierung

🔧 How to Build a Secure User Authentication Flow in Flutter with Firebase and Bloc State Management


📈 24.24 Punkte
🔧 Programmierung

🎥 Technical Debt and Streams/BLoC - The Boring Flutter Development Show, Ep. 4


📈 24.24 Punkte
🎥 Videos

🕵️ Nation States Are Using Cyber Crime Groups to Carry Attacks: States Blackberry Threat Report 2021


📈 23.8 Punkte
🕵️ Hacking

📰 48-Nation Bloc To Crack Down On Using Crypto Assets To Avoid Tax


📈 22.87 Punkte
📰 IT Security Nachrichten

📰 Excel: Daten aus dem Internet en bloc importieren


📈 22.87 Punkte
📰 IT Nachrichten

🔧 The Ultimate Guide to Flutter Lists with Bloc : Part 3


📈 22.87 Punkte
🔧 Programmierung

📰 EU Set To Unveil Plans For Bloc-Wide Digital Wallet


📈 22.87 Punkte
📰 IT Security Nachrichten

🔧 Flutter BLoC Architecture


📈 22.87 Punkte
🔧 Programmierung

🔧 🚀 State Management Smackdown: Riverpod vs Provider vs BLoC 🥊


📈 22.87 Punkte
🔧 Programmierung

📰 15 Asia-Pacific Countries Form World's Largest Trade Bloc, Exclude the US


📈 22.87 Punkte
📰 IT Security Nachrichten

🔧 The Ultimate Guide to Flutter Lists with Bloc : Part 2


📈 22.87 Punkte
🔧 Programmierung

📰 Firefox: Cookies selektiv und en bloc löschen


📈 22.87 Punkte
📰 IT Nachrichten

🔧 The Ultimate Guide to Flutter Lists with Bloc : Part 1


📈 22.87 Punkte
🔧 Programmierung

🔧 Utiliser async/await sans bloc try..catch !


📈 22.87 Punkte
🔧 Programmierung

🔧 Flutter Design Pattern Bussines Logic Component (BLOC)


📈 22.87 Punkte
🔧 Programmierung

🔧 BLoC - Mais que um package, um padrão


📈 22.87 Punkte
🔧 Programmierung

🔧 Cubit VS Bloc in Flutter


📈 22.87 Punkte
🔧 Programmierung

🔧 How to Write BLoC Tests to Improve Code Quality


📈 22.87 Punkte
🔧 Programmierung

📰 Meta Warns EU Regulatory Efforts Risk Bloc Missing Out on AI Advances


📈 22.87 Punkte
📰 IT Security Nachrichten

🔧 How to Migrate a Flutter Application from GetIt to Bloc


📈 22.87 Punkte
🔧 Programmierung