2.7 KiB
Bloc Counter
As projects get bigger and more complex, managing all the widgets, their states, and updating their children's states can become troublesome. To avoid potential complexity, it is recommended to use Patterns. Patterns are built to help developers control the hierarchy of widgets more easily, and one popular pattern in Flutter is BLoC
.
In this project, you will implement a simple counter app
,like the example bellow, using the BLoC
pattern. When you start writing your own application, structuring it correctly is important.
Instructions
- Observe state changes with
BlocObserver
. - Use
BlocProvider
, a Flutter widget which provides a bloc to its children. - Use
BlocBuilder
, a Flutter widget that handles building the widget in response to new states.
BLoC
pattern uses reactive programming to handle the flow of data within an app.
A Bloc consists of 2 concepts, Streams
and Sinks
, which are provided by StreamController
.
💡 See this article Architect your Flutter project using BLoC pattern, by Sagar Suri.
💡 Documentation https://bloclibrary.dev/#/gettingstarted.
Project Setup
- Create a new Flutter app, so it generates a sample Counter App.
- Add
flutter_bloc
as a dependency to your app.
Your app structure should be similar to:
—lib
—bloc
—counter_bloc.dart
—counter_event.dart
-widgets
—yourwidgets.dart
—..
—main.dart
Bloc Implementation
- Add an enum to
bloc/couter_event.dart
.
enum CounterEvent {
increment
}
- Go to
bloc/counter_bloc.dart
and create aCounterBloc
class that extendsCounterBloc
.
Note: you can generate bloc files using vscode extension.
- Implement an override of the
mapEventToState
function in theCounterBloc
class, so it switches between different events and returns the value as anint
. In our case, we only have a case with an increment state.
UI and getting data
- Inside the
MyApp
class, wrap your home page with aBlocProvider
class.
return MaterialApp(
home: BlocProvider<CounterBloc>(
create: (context) => CounterBloc(),
child: Home(),
),
);
- Inside the
Home
class, create an instance of theCounterBloc
class. - Use
BlocBuilder
to state fromCounterBloc
. - Add a "+" button to call
CounterEvent.increment
.
Bonus
- Add button and event to handle decrementing the counter.