Using BLoC/Cubit for Architectural Patterns in Flutter

Flutter has become a prominent choice for building cross-platform applications, offering a rich set of tools and widgets to create stunning user interfaces. As applications grow in complexity, employing robust architectural patterns becomes essential for maintainability, testability, and scalability. Among the various patterns, the BLoC (Business Logic Component) and Cubit patterns have gained significant traction. This article explores how to effectively use BLoC/Cubit for architectural patterns in Flutter applications, providing a comprehensive guide with detailed examples.

What is BLoC and Cubit?

BLoC and Cubit are state management solutions popularized by Flutter. They provide a way to separate business logic from the presentation layer, making your code more organized, testable, and reusable. Both are based on the concept of streams of events transforming into streams of states, but they differ in their implementation details.

BLoC (Business Logic Component)

BLoC is an architectural pattern where the business logic is encapsulated within a separate component that handles input events and produces output states. It relies heavily on the Reactive Programming principles and uses Streams and Sinks for event and state management.

Cubit

Cubit is a lighter and simpler alternative to BLoC. It is built on top of BLoC but simplifies the implementation by using methods instead of streams to manage state changes. Cubits are generally easier to understand and implement, making them suitable for simpler applications or components.

Why Use BLoC/Cubit in Flutter?

  • Separation of Concerns: Separates the business logic from the UI layer, promoting a cleaner and more maintainable codebase.
  • Testability: Simplifies unit testing by allowing you to test the business logic in isolation.
  • Reusability: Enables reuse of business logic components across different parts of the application.
  • State Management: Provides a clear and predictable way to manage the application state.
  • Scalability: Facilitates scaling the application by organizing the codebase into manageable components.

Setting Up Your Flutter Project

Before diving into the implementation, ensure you have a Flutter project set up. You can create a new project using the following command:

flutter create my_flutter_app
cd my_flutter_app

Adding Dependencies

To use BLoC/Cubit in your project, you need to add the flutter_bloc package to your pubspec.yaml file:

dependencies:
  flutter:
    sdk: flutter
  flutter_bloc: ^8.1.3

Run flutter pub get to install the dependencies.

Implementing BLoC

Let’s create a simple counter application using the BLoC pattern. This will involve creating an event, a state, and a BLoC class.

Step 1: Define Events

Create a new file counter_event.dart to define the events that the counter BLoC will handle:

import 'package:equatable/equatable.dart';

abstract class CounterEvent extends Equatable {
  @override
  List get props => [];
}

class IncrementCounterEvent extends CounterEvent {}

class DecrementCounterEvent extends CounterEvent {}

Step 2: Define States

Create a new file counter_state.dart to define the states of the counter BLoC:

import 'package:equatable/equatable.dart';

class CounterState extends Equatable {
  final int counter;

  const CounterState({required this.counter});

  @override
  List get props => [counter];
}

Step 3: Create the BLoC

Create a new file counter_bloc.dart to implement the counter BLoC:

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

class CounterBloc extends Bloc&ltCounterEvent, CounterState&gt {
  CounterBloc() : super(const CounterState(counter: 0)) {
    on&ltIncrementCounterEvent&gt((event, emit) {
      emit(CounterState(counter: state.counter + 1));
    });
    on&ltDecrementCounterEvent&gt((event, emit) {
      emit(CounterState(counter: state.counter - 1));
    });
  }
}

Step 4: Implement the UI

Modify your main.dart file to use the CounterBloc and display the counter value:

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

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter BLoC Counter',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: BlocProvider(
        create: (context) => CounterBloc(),
        child: const CounterPage(),
      ),
    );
  }
}

class CounterPage extends StatelessWidget {
  const CounterPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Flutter BLoC Counter'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: &ltWidget&gt[
            const Text(
              'Counter Value:',
              style: TextStyle(fontSize: 20),
            ),
            BlocBuilder&ltCounterBloc, CounterState&gt(
              builder: (context, state) {
                return Text(
                  '${state.counter}',
                  style: const TextStyle(fontSize: 40, fontWeight: FontWeight.bold),
                );
              },
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: &ltWidget&gt[
                FloatingActionButton(
                  onPressed: () {
                    context.read&ltCounterBloc&gt().add(IncrementCounterEvent());
                  },
                  tooltip: 'Increment',
                  child: const Icon(Icons.add),
                ),
                const SizedBox(width: 20),
                FloatingActionButton(
                  onPressed: () {
                    context.read&ltCounterBloc&gt().add(DecrementCounterEvent());
                  },
                  tooltip: 'Decrement',
                  child: const Icon(Icons.remove),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

Implementing Cubit

Let’s implement the same counter application using the Cubit pattern for comparison.

Step 1: Define States

The state definition remains the same as in the BLoC example. Ensure you have the counter_state.dart file with the CounterState class.

Step 2: Create the Cubit

Create a new file counter_cubit.dart to implement the counter Cubit:

import 'package:flutter_bloc/flutter_bloc.dart';
import 'counter_state.dart';

class CounterCubit extends Cubit&ltCounterState&gt {
  CounterCubit() : super(const CounterState(counter: 0));

  void increment() {
    emit(CounterState(counter: state.counter + 1));
  }

  void decrement() {
    emit(CounterState(counter: state.counter - 1));
  }
}

Step 3: Implement the UI

Modify your main.dart file to use the CounterCubit and display the counter value:

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

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Cubit Counter',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: BlocProvider(
        create: (context) => CounterCubit(),
        child: const CounterPage(),
      ),
    );
  }
}

class CounterPage extends StatelessWidget {
  const CounterPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Flutter Cubit Counter'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: &ltWidget&gt[
            const Text(
              'Counter Value:',
              style: TextStyle(fontSize: 20),
            ),
            BlocBuilder&ltCounterCubit, CounterState&gt(
              builder: (context, state) {
                return Text(
                  '${state.counter}',
                  style: const TextStyle(fontSize: 40, fontWeight: FontWeight.bold),
                );
              },
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: &ltWidget&gt[
                FloatingActionButton(
                  onPressed: () {
                    context.read&ltCounterCubit&gt().increment();
                  },
                  tooltip: 'Increment',
                  child: const Icon(Icons.add),
                ),
                const SizedBox(width: 20),
                FloatingActionButton(
                  onPressed: () {
                    context.read&ltCounterCubit&gt().decrement();
                  },
                  tooltip: 'Decrement',
                  child: const Icon(Icons.remove),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

Differences Between BLoC and Cubit

  • Complexity: BLoC is more complex due to the use of Streams and Sinks, whereas Cubit is simpler with methods for state changes.
  • Events vs. Methods: BLoC uses events to trigger state changes, while Cubit directly uses methods.
  • Boilerplate Code: BLoC often requires more boilerplate code for event and state management compared to Cubit.

When to Use BLoC vs. Cubit

  • BLoC: Use BLoC for complex applications with intricate business logic that requires reactive programming and event-driven state management.
  • Cubit: Use Cubit for simpler applications or components where the business logic is straightforward and the need for reactive programming is minimal.

Advanced Topics

Using BlocListener and BlocConsumer

BlocListener can be used to perform side effects in response to state changes without affecting the UI. BlocConsumer combines the functionality of BlocBuilder and BlocListener.

BlocListener&ltCounterBloc, CounterState&gt(
  listener: (context, state) {
    if (state.counter > 10) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('Counter has exceeded 10!')),
      );
    }
  },
  child: BlocBuilder&ltCounterBloc, CounterState&gt(
    builder: (context, state) {
      return Text(
        '${state.counter}',
        style: const TextStyle(fontSize: 40, fontWeight: FontWeight.bold),
      );
    },
  ),
)

Testing BLoC/Cubit

Testing BLoC and Cubit components is crucial for ensuring the reliability of your application. The bloc_test package simplifies this process.

dev_dependencies:
  flutter_test:
    sdk: flutter
  bloc_test: ^9.1.4

Here’s an example of how to test a CounterBloc:

import 'package:bloc_test/bloc_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:my_flutter_app/counter_bloc.dart';
import 'package:my_flutter_app/counter_event.dart';
import 'package:my_flutter_app/counter_state.dart';

void main() {
  group('CounterBloc', () {
    blocTest&ltCounterBloc, CounterState&gt(
      'emits [CounterState(counter: 1)] when IncrementCounterEvent is added',
      build: () => CounterBloc(),
      act: (bloc) => bloc.add(IncrementCounterEvent()),
      expect: () => [const CounterState(counter: 1)],
    );

    blocTest&ltCounterBloc, CounterState&gt(
      'emits [CounterState(counter: -1)] when DecrementCounterEvent is added',
      build: () => CounterBloc(),
      act: (bloc) => bloc.add(DecrementCounterEvent()),
      expect: () => [const CounterState(counter: -1)],
    );
  });
}

Conclusion

BLoC and Cubit are powerful architectural patterns for managing state and business logic in Flutter applications. By separating the UI layer from the business logic, you can create more maintainable, testable, and scalable applications. Whether you choose BLoC or Cubit depends on the complexity of your application and your familiarity with reactive programming principles. Properly implementing and testing your BLoC/Cubit components can significantly improve the robustness and reliability of your Flutter projects.