我已经使用 flutter_bloc 包实现了一个简单的块:
class MainBloc extends Bloc<MainEvent, MainState> {
@override
MainState get initialState => Init();
@override
Stream<MainState> mapEventToState(MainEvent event) async* {
if (event is Event) {
yield* _mapEventToState();
}
}
Stream<MainState> _mapEventToState() async* {
final loadState = Load();
print("Yield state: $loadState");
yield loadState;
await sleep(Duration(seconds: 1));
final initState = Init();
print("Yield state: $initState");
yield initState;
}
}
与此事件:
abstract class MainEvent {}
class Event extends MainEvent {}
这个状态:
abstract class MainState {}
class Load extends MainState {}
class Init extends MainState {}
我的用户界面如下所示:
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Material App',
home: BlocProvider(
create: (context) => MainBloc(),
child: Scaffold(
appBar: AppBar(),
body: BlocBuilder<MainBloc, MainState>(
builder: (context, state) {
print("Build state: $state");
if (state is Init) {
return MaterialButton(
onPressed: () => BlocProvider.of<MainBloc>(context).add(Event()),
child: Text("Press"),
);
} else {
return Text("Loading");
}
},
),
),
),
);
}
}
不幸的是,如果我使用 MaterialButton 添加我的事件,则 Load() 状态将被忽略。UI 不会重建 Load 状态。输出如下:
I/flutter (1955):屈服状态:“负载”实例
I/flutter (1955):屈服状态:“初始化”实例
I/flutter (1955):构建状态:“Init”实例