How to use BLoC Architecture?

This example assumes that you are using the flutter_bloc package, which is a popular package for managing state in Flutter applications.

First, make sure to add the flutter_bloc package to your pubspec.yaml file:

Then, create a new file called my_bloc.dart and add the following code:

In this example:

  • We have two events (IncrementEvent and DecrementEvent) representing actions that can trigger state changes.
  • We have a simple state (MyState) with a counter value.
  • The MyBloc class extends Bloc<MyEvent, MyState> and overrides the mapEventToState method to handle events and emit new states accordingly.

To use this BLoC in your Flutter widget, you would typically wrap your widget with a BlocProvider and access the BLoC using BlocBuilder or BlocListener. Here’s a simple example:

This example sets up a simple Flutter app with a BLoC managing the state. The UI updates based on the counter value in the BLoC. The Increment and Decrement buttons trigger the corresponding events, updating the state and causing the UI to re-render.

Leave a Reply

Your email address will not be published. Required fields are marked *