一个Flutter BLoC入门的简单 demo
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
// 定义事件
enum CounterEvent { increment, decrement }
// 创建BLoC
class CounterBloc extends Bloc<CounterEvent, int> {
@override
int get initialState => 0;
@override
Stream<int> mapEventToState(CounterEvent event) async* {
switch (event) {
case CounterEvent.increment:
yield state + 1;
break;
case CounterEvent.decrement:
yield state - 1;
break;
}
}
}
void main() {
runApp(BlocProvider(
create: (context) => CounterBloc(),
child: MyApp(),
));
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: BlocBuilder<CounterBloc, int>(
builder: (context, count) {
return Scaffold(
body: Center(
child: Text('$count'),
),
floatingActionButton: Column(
crossAxisAlignment: CrossAxisAlignment.end,
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
FloatingActionButton(
child: Icon(Icons.add),
onPressed: () => BlocProvider.of<CounterBloc>(context).add(CounterEvent.increment),
),
SizedBox(height: 10),
FloatingActionButton(
child: Icon(Icons.remove),
onPressed: () => BlocProvider.of<CounterBloc>(context).add(CounterEvent.decrement),
),
],
),
);
},
),
);
}
}
这个简单的Flutter BLoC Demo展示了如何创建和使用一个BLoC来管理应用程序状态,这里的状态是一个整数计数器。BLoC监听来自FloatingActionButton的事件,并根据事件更新状态,在Text组件中显示当前状态。这个例子是入门级别的,但它展示了BLoC模式的基本概念。
评论已关闭