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:
dependencies:
flutter:
sdk: flutter
flutter_bloc: ^7.0.0
Then, create a new file called my_bloc.dart and add the following code:
import 'package:flutter_bloc/flutter_bloc.dart';
// Events
abstract class MyEvent {}
class IncrementEvent extends MyEvent {}
class DecrementEvent extends MyEvent {}
// States
class MyState {
final int counter;
MyState(this.counter);
}
// BLoC
class MyBloc extends Bloc<MyEvent, MyState> {
MyBloc() : super(MyState(0));
@override
Stream<MyState> mapEventToState(MyEvent event) async* {
if (event is IncrementEvent) {
yield MyState(state.counter + 1);
} else if (event is DecrementEvent) {
yield MyState(state.counter - 1);
}
}
}
In this example:
- We have two events (
IncrementEventandDecrementEvent) representing actions that can trigger state changes. - We have a simple state (
MyState) with a counter value. - The
MyBlocclass extendsBloc<MyEvent, MyState>and overrides themapEventToStatemethod 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:
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: BlocProvider(
create: (context) => MyBloc(),
child: MyHomePage(),
),
);
}
}
class MyHomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('BLoC Example'),
),
body: BlocBuilder<MyBloc, MyState>(
builder: (context, state) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('Counter: ${state.counter}'),
SizedBox(height: 20),
ElevatedButton(
onPressed: () {
context.read<MyBloc>().add(IncrementEvent());
},
child: Text('Increment'),
),
ElevatedButton(
onPressed: () {
context.read<MyBloc>().add(DecrementEvent());
},
child: Text('Decrement'),
),
],
),
);
},
),
);
}
}
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.