Using Bloc for State Management

Bloc (Business Logic Component) is a popular state management solution in Flutter that leverages reactive programming principles. It uses streams to handle events and manage state, separating business logic from the UI.

Here's a step-by-step example to demonstrate how to use Bloc for state management:

  1. Add Dependencies

First, add the flutter_bloc and bloc packages to your pubspec.yaml file:

dependencies:
  flutter:
    sdk: flutter
  flutter_bloc: ^8.0.0
  bloc: ^8.0.0
  1. Create the Counter Bloc

Define the events and states for the Bloc.

counter_event.dart:

abstract class CounterEvent {}

class IncrementCounter extends CounterEvent {}

counter_state.dart:

class CounterState {
  final int count;

  CounterState(this.count);
}

counter_bloc.dart:

import 'package:bloc/bloc.dart';
import 'counter_event.dart';
import 'counter_state.dart';

class CounterBloc extends Bloc<CounterEvent, CounterState> {
  CounterBloc() : super(CounterState(0));

  @override
  Stream<CounterState> mapEventToState(CounterEvent event) async* {
    if (event is IncrementCounter) {
      yield CounterState(state.count + 1);
    }
  }
}
  1. Set Up Bloc in main.dart

Wrap your app with the BlocProvider to provide the Bloc to the widget tree.

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'counter_bloc.dart';
import 'counter_event.dart';
import 'counter_state.dart';

void main() {
  runApp(
    BlocProvider(
      create: (context) => CounterBloc(),
      child: MyApp(),
    ),
  );
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: CounterScreen(),
    );
  }
}
  1. Create the Counter Screen

Use BlocBuilder to rebuild the UI based on the current state.

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'counter_bloc.dart';
import 'counter_event.dart';
import 'counter_state.dart';

class CounterScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Bloc Example')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text('You have pushed the button this many times:'),
            BlocBuilder<CounterBloc, CounterState>(
              builder: (context, state) {
                return Text(
                  '${state.count}',
                  style: Theme.of(context).textTheme.headline4,
                );
              },
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () => context.read<CounterBloc>().add(IncrementCounter()),
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

Summary

Bloc is a powerful state management solution in Flutter that uses streams to manage state and handle events. By separating business logic from the UI, Bloc helps you maintain clean and scalable code. In this example, we've demonstrated how to set up a simple counter application using Bloc, showing how to define events and states, create a Bloc, and use BlocBuilder to update the UI based on state changes. This approach ensures a reactive and well-structured application architecture.

Did you find this article valuable?

Support Michael Piper by becoming a sponsor. Any amount is appreciated!