How to Use Bloc for State Management in Flutter

Tutorial 5 of 5

Flutter Tutorial: Using Bloc for State Management

Introduction

In this tutorial, we will be learning about Bloc (Business Logic Component), a popular library used for state management in Flutter. State management is a crucial aspect of any application, and Bloc allows for an organized, clean separation of business logic from UI.

By the end of this tutorial, you will understand:

  • What is Bloc and its role in state management
  • How to set up and use Bloc in a Flutter application
  • Best practices when using Bloc

Prerequisites: Basic knowledge of Flutter and Dart language is required.

Step-by-Step Guide

Bloc uses the concept of Events and States. An Event is dispatched by the UI to the Bloc, which causes it to produce a new State that is then rendered back to the UI.

  1. BlocProvider: This is a Flutter widget that provides a Bloc to its children. BlocProvider should be used when we want to provide a newly created Bloc.

  2. BlocBuilder: This is a Flutter widget that requires a Bloc and a builder function. BlocBuilder handles building the widget in response to new states.

  3. BlocListener: This is a Flutter widget that takes a Bloc and a listener function. BlocListener is used for functionality that should occur only once per Bloc state (like navigation, showing a SnackBar, etc).

Let's dive into some code examples.

Code Examples

BlocProvider Example:

BlocProvider(
  create: (BuildContext context) => MyBloc(),
  child: MyWidget(),
);

In this example, BlocProvider is providing a new instance of MyBloc to MyWidget. The MyBloc instance will be available to all children of MyWidget.

BlocBuilder Example:

BlocBuilder<MyBloc, MyState>(
  builder: (context, state) {
    if (state is LoadingState) {
      return CircularProgressIndicator();
    }
    if (state is LoadedState) {
      return ListView.builder(
        itemCount: state.listItems.length,
        itemBuilder: (_, index) => ListTile(title: Text(state.listItems[index])),
      );
    }
  },
);

In this example, the UI will display a CircularProgressIndicator when the state is LoadingState, and a ListView when the state is LoadedState.

BlocListener Example:

BlocListener<MyBloc, MyState>(
  listener: (context, state) {
    if (state is ErrorState) {
      Scaffold.of(context).showSnackBar(
        SnackBar(content: Text(state.message)),
      );
    }
  },
  child: AnyWidget(),
);

In this example, a SnackBar with the error message from ErrorState is shown whenever the Bloc state changes to ErrorState.

Summary

In this tutorial, we learned about Bloc and how it's used in Flutter for state management. We covered the key components: BlocProvider for providing Blocs, BlocBuilder for building UI in response to state changes, and BlocListener for executing code once per state change.

To continue learning, you can:
- Dive deeper into Bloc's documentation
- Explore other state management solutions in Flutter
- Practice your new skills with exercises

Practice Exercises

  1. Exercise 1: Create a Bloc that has an initial state of EmptyState and can transition to LoadingState, LoadedState with a List of numbers from 0-10, and ErrorState with a custom error message.

  2. Exercise 2: Create a UI that dispatches a LoadListEvent when a button is pressed, shows a loading indicator in LoadingState, displays the list in LoadedState, and shows a SnackBar with the error message in ErrorState.

Hint: Remember that the Bloc should handle mapping the LoadListEvent to the appropriate states.

For further practice, you can try adding more complex states and events, or use Bloc in a larger application. Happy coding!