我有一个main.dart
及其自己的main_bloc.dart
,main_event.dart
和main_state.dart
:
main_event:
- AppStarted
- GoingHome
- GoingTestHome
main_State:
- StateHome
- StateTestHome
main_bloc:
Stream<MainState> mapEventToState(
MainEvent event,
) async* {
if (event is AppStarted) {
print('mainbloc: AppStarted');
dispatch(GoingHome());
}
if (event is GoingHome) {
print('mainbloc: GoingHome');
yield StateHome();
}
if (event is TestHome) {
print('mainbloc: TestHome');
yield StateTestHome();
}
...
}
在我的main.dart
中:
class _AppState extends State<App> {
MainBloc _mainBloc;
@override
void initState() {
super.initState();
_mainBloc = MainBloc();
_mainBloc.dispatch(AppStarted());/// <-- 1
}
...
@override
Widget build(BuildContext context) {
return BlocProvider(
builder: (_) => _mainBloc,
child: MaterialApp(
title: 'Home',
theme: ThemeData(
...
),
home: BlocListener<MainBloc, MainState>(
bloc: _mainBloc,
listener: (context, state) {
print('state changed: ${state.toString()}');
if (state is StateHome) { /// <-- 2
print('main: StateHome');
_mainBloc.dispatch(TestHome()); /// <-- 2.1
} else if (state is StateTestHome) { /// <-- 3
print('main: StateTestHome');
}
},
child: SplashPage()),
...
我做一个快速测试:
_mainBloc.dispatch(AppStarted())
,它将从dispatch(GoingHome())
调用main_bloc
。 BlocListener
检测到状态更改(“ StateHome”),因此:
print('main: StateHome');
_mainBloc.dispatch(TestHome());
BlocListener
再次检测到状态更改('StateTestHome'),因此:
print('main: StateTestHome');
在控制台中,我可以依次看到所有打印消息:
Restarted application in 1,612ms.
I/flutter (15369): mainbloc: AppStarted
I/flutter (15369): mainbloc: GoingHome
I/flutter (15369): state changed: StateHome
I/flutter (15369): main: StateHome
I/flutter (15369): mainbloc: TestHome
I/flutter (15369): state changed: StateTestHome
I/flutter (15369): main: StateTestHome
到目前为止,它以我预期的方式运行。
但是当我取出代码2.1
时,然后添加一个按钮来触发事件:
...
floatingActionButton: FloatingActionButton(
child: Text('test'),
onPressed: () {
_mainBloc.dispatch(TestHome());
},
),
...
我将获得这样的控制台:
Restarted application in 2,738ms.
I/flutter (15369): mainbloc: AppStarted
I/flutter (15369): mainbloc: GoingHome
I/flutter (15369): state changed: StateHome
I/flutter (15369): main: StateHome
I/flutter (15369):
I/flutter (15369): mainbloc: TestHome ///<-- button trigger
我希望:
Restarted application in 2,738ms.
I/flutter (15369): mainbloc: AppStarted
I/flutter (15369): mainbloc: GoingHome
I/flutter (15369): state changed: StateHome
I/flutter (15369): main: StateHome
I/flutter (15369):
I/flutter (15369): mainbloc: TestHome ///<-- button trigger
I/flutter (15369): state changed: StateTestHome ///<-- expectation
I/flutter (15369): main: StateTestHome ///<-- expectation
似乎按钮交互没有yield
状态,或者BlocListener
没有捕获状态更改事件。
我在这里想念什么?我该如何解决?
答案 0 :(得分:1)
Bloc
捕获了事件,但是您尝试发送连续的相同状态。在yield StateTestHome();
喜欢
yield StateIgnored(); // *****
yield StateTestHome();
答案 1 :(得分:0)
我发现了问题。
blocListener
仅针对事件child
监听事件。我所做的就是让它侦听child
(直接child
的{{1}})内的子小部件触发的事件,这样就不会发生。
要解决此问题,请为直接child
本身的blocListener
创建一个child
。