introduction to how BLoC works in Flutter
By | 4 months ago
Let's break down the BLoC (Business Logic Component) architecture more thoroughly to ensure you understand how it helps manage state in Flutter applications.
What is BLoC?
BLoC is a design pattern used in Flutter to separate the business logic from the user interface (UI). It stands for Business Logic Component. The main goal of BLoC is to manage state and business logic globally or locally in an app without having the UI components hold any state themselves.
Core Components of BLoC
-
**Events**: These are inputs from the UI, such as user interactions (button clicks, swipes, etc.) that trigger actions in a BLoC.
-
**States**: These are outputs from the BLoC that represent parts of the application's state at a given point in time.
-
**BLoC/Streams**: The BLoC listens to events, performs business logic, and then emits states through streams.
How BLoC Works
Here’s a simplified overview of the workflow:
-
**UI sends Events**: The user does something that interacts with the UI, like pressing a button. This interaction triggers an event.
-
**BLoC processes Events**: The BLoC listens to these events, performs necessary calculations or data fetching, and then decides what the new state should be.
-
**BLoC emits States**: Once the new state is determined, the BLoC emits this state.
-
**UI reacts to State changes**: The UI listens to the state changes from the BLoC and updates accordingly. This could be anything from showing a loading spinner, displaying data, or showing an error message.
Example Walkthrough
Let's use a simple counter app as an example to demonstrate the implementation of the BLoC pattern:
Step 1: Define Events and States
First, define the types of events the UI can send and the types of states the BLoC can emit:
// Events abstract class CounterEvent {} class Increment extends CounterEvent {} class Decrement extends CounterEvent {} // States abstract class CounterState {} class CounterValue extends CounterState { final int value; CounterValue(this.value); }
Step 2: Create the BLoC
Next, implement the BLoC that listens for events and emits states:
import 'package:flutter_bloc/flutter_bloc.dart'; class CounterBloc extends Bloc<CounterEvent, CounterState> { CounterBloc() : super(CounterValue(0)) { // Initial state on<Increment>((event, emit) { final currentState = state; if (currentState is CounterValue) { emit(CounterValue(currentState.value + 1)); // Emit new state with incremented value } }); on<Decrement>((event, emit) { final currentState = state; if (currentState is CounterValue) { emit(CounterValue(currentState.value - 1)); // Emit new state with decremented value } }); } }
Step 3: Connect BLoC to UI
Finally, use the BLoC in the UI with `BlocProvider` and BlocBuilder
:
class CounterPage extends StatelessWidget { Widget build(BuildContext context) { return BlocProvider( create: (context) => CounterBloc(), child: BlocBuilder<CounterBloc, CounterState>( builder: (context, state) { int count = 0; if (state is CounterValue) { count = state.value; } return Scaffold( appBar: AppBar(title: Text("Counter")), body: Center( child: Text('$count', style: Theme.of(context).textTheme.headline4), ), floatingActionButton: Row( mainAxisAlignment: MainAxisAlignment.end, children: <Widget>[ FloatingActionButton( onPressed: () => context.read<CounterBloc>().add(Increment()), tooltip: 'Increment', child: Icon(Icons.add), ), SizedBox(width: 10), FloatingActionButton( onPressed: () => context.read<CounterBloc>().add(Decrement()), tooltip: 'Decrement', child: Icon(Icons.remove), ), ], ), ); }, ), ); } }
Benefits of Using BLoC
-
**Maintainability**: Since BLoC separates business logic from UI code, it simplifies maintenance and scalability.
-
**Testability**: BLoC components are easy to test since they are decoupled from the UI.
-
**Reactivity**: BLoC leverages Dart’s streams for state management, ensuring that components can reactively update when the state changes.
The BLoC architecture helps manage state effectively by clearly separating concerns and using reactive programming principles, making it easier to manage complex state in larger applications.