Learn how to implement a simple counter application using the Bloc pattern in Flutter, leveraging flutter_bloc for state management.
In this section, we will explore how to create a simple counter application using the Bloc pattern in Flutter. The Bloc pattern is a powerful state management solution that helps separate business logic from the UI, making your code more modular and testable. We’ll use the flutter_bloc
package to implement this pattern efficiently.
To get started, let’s create a new Flutter project. Open your terminal and run the following command:
flutter create bloc_counter_app
Navigate into the project directory:
cd bloc_counter_app
Open the project in your preferred IDE, such as Visual Studio Code or Android Studio.
In the Bloc pattern, events are the inputs to the Bloc. They represent user actions or occurrences in the app that require a response. For our counter app, we’ll define two events: increment and decrement.
Create a new file named counter_event.dart
in the lib
directory and add the following code:
abstract class CounterEvent {}
class IncrementEvent extends CounterEvent {}
class DecrementEvent extends CounterEvent {}
Here, CounterEvent
is an abstract class, and IncrementEvent
and DecrementEvent
are concrete implementations representing the actions to increase or decrease the counter.
Next, we’ll define the Bloc itself, which will handle the logic for updating the counter based on the events received.
Create a new file named counter_bloc.dart
in the lib
directory and add the following code:
import 'package:flutter_bloc/flutter_bloc.dart';
import 'counter_event.dart';
class CounterBloc extends Bloc<CounterEvent, int> {
CounterBloc() : super(0) {
on<IncrementEvent>((event, emit) => emit(state + 1));
on<DecrementEvent>((event, emit) => emit(state - 1));
}
}
CounterBloc
takes CounterEvent
as input and outputs an int
(the counter value).0
.IncrementEvent
and DecrementEvent
by updating the state using the emit
function.Now, let’s build the UI for our counter app. We’ll create a simple interface with two buttons to increment and decrement the counter and a text widget to display the current count.
Open the lib/main.dart
file and replace its content with the following code:
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'counter_bloc.dart';
import 'counter_event.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: BlocProvider(
create: (context) => CounterBloc(),
child: CounterPage(),
),
);
}
}
class CounterPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Bloc Counter')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
BlocBuilder<CounterBloc, int>(
builder: (context, count) {
return Text(
'$count',
style: TextStyle(fontSize: 24.0),
);
},
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
IconButton(
icon: Icon(Icons.add),
onPressed: () {
context.read<CounterBloc>().add(IncrementEvent());
},
),
IconButton(
icon: Icon(Icons.remove),
onPressed: () {
context.read<CounterBloc>().add(DecrementEvent());
},
),
],
),
],
),
),
);
}
}
CounterBloc
to the widget tree, making it accessible to all descendant widgets.CounterBloc
and updates the text widget with the current count.IncrementEvent
and DecrementEvent
to the CounterBloc
when pressed.In the UI code, we use context.read<CounterBloc>().add(IncrementEvent())
to dispatch events. This triggers the corresponding handler in the Bloc, updating the state and consequently the UI.
To run the app, use the following command in your terminal:
flutter run
This will launch the app on your connected device or emulator. You should see a simple interface with two buttons and a counter display. Pressing the “+” button will increment the counter, while pressing the “-” button will decrement it.
To better understand the flow of data in our app, let’s visualize the process from user interaction to UI update using a Mermaid.js diagram:
graph LR; UserClick --> DispatchEvent; DispatchEvent --> Bloc; Bloc --> EmitState; EmitState --> UIUpdate;
By following these steps, you have successfully implemented a simple counter app using the Bloc pattern in Flutter. This foundational understanding will help you build more complex applications with robust state management.
To deepen your understanding of the Bloc pattern and its applications, consider exploring the following resources: