What is BLoC in Flutter: Explanation and Example
BLoC stands for Business Logic Component, a design pattern that helps separate app logic from UI by using streams to manage state. It makes your app easier to test and maintain by organizing how data flows and changes in response to user actions.How It Works
The BLoC pattern works like a smart assistant that listens to your app's events (like button taps) and then decides what should happen next. It uses streams to send data back and forth between the UI and the logic part of your app.
Think of it like a post office: the UI sends messages (events) to the BLoC, which processes them and sends back updated information (states) that the UI can show. This keeps your UI simple and focused only on displaying data, while the BLoC handles all the thinking and rules.
Example
This example shows a simple counter app using BLoC. The user taps a button to increase the count, and the BLoC updates the number displayed.
import 'dart:async'; import 'package:flutter/material.dart'; // BLoC class class CounterBloc { int _count = 0; final _stateController = StreamController<int>(); Stream<int> get countStream => _stateController.stream; void increment() { _count++; _stateController.sink.add(_count); } void dispose() { _stateController.close(); } } void main() => runApp(MyApp()); class MyApp extends StatelessWidget { final CounterBloc bloc = CounterBloc(); @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: Text('BLoC Counter Example')), body: Center( child: StreamBuilder<int>( stream: bloc.countStream, initialData: 0, builder: (context, snapshot) { return Text('Count: ${snapshot.data}', style: TextStyle(fontSize: 30)); }, ), ), floatingActionButton: FloatingActionButton( onPressed: bloc.increment, child: Icon(Icons.add), ), ), ); } }
When to Use
Use BLoC when your app has complex state changes or when you want to keep your UI code clean and easy to manage. It is especially helpful in apps with many user interactions or data updates, like chat apps, shopping carts, or forms.
It also makes testing easier because your business logic is separate from the UI, so you can test it without needing to run the whole app.
Key Points
- BLoC separates business logic from UI using streams.
- It listens to events and outputs states to update the UI.
- Helps keep code organized, testable, and maintainable.
- Works well for apps with complex or frequent state changes.