![](/img/trans.png)
[英]flutter: Unhandled Exception: Bad state: Cannot add new events after calling close
[英]Unhandled Exception: Bad state: Cannot add new events after calling close - Between screens
我有下一个架构:
ScreenA > ScreenB
/// Here i navigate from ScreenA to ScreenB, so here i create the BlocB that i'm going to use
BlocProvider<BlocB>(
create: (context) => BlocB(),
child: const ScreenB(),
),
ScreenB > ScreenC
await Navigator.of(context).pushReplacementNamed(
PageNames.screenC,
arguments: context.read<BlocB>(),
);
/// Here i navigate from ScreenB to ScreenC, so i re-value the BlocB
BlocProvider<BlocB>.value(
value: (args as BlocB),
child: const ScreenC(),
),
在这里,我执行相同的逻辑,直到 ScreenD 我将使用 BlocListener 并从 BlocB 执行添加事件
ScreenC > ScreenD
await Navigator.pushNamed(
context,
PageNames.screenD,
arguments: context.read<BlocB>(),
);
/// Here i navigate from ScreenC to ScreenD, so i re-value the BlocB
BlocProvider<BlocB>.value(
value: (args as BlocB),
child: const ScreenD(),
),
BlocF 监听器
return BlocListener<BlocF, BlocFState>(
listener: (context, state) {
if (state.status.isSuccess) {
context.read<BlocB>().add(someEvent()); // error
}
},
child: child...
现在,我将使用来自另一个 Bloc(例如 BlocF)的添加事件,现在发送一个状态和它的侦听器,我想从 BlocB 添加事件,但是我有错误:
[ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: Bad state: Cannot add new events after calling close
我不知道为什么如果我穿过我的 Bloc 的屏幕
该错误消息表明在BlocListener
的ScreenF
中使用的BlocB
实例不再有效。 如果在离开ScreenA
时关闭或处置BlocB
实例,然后尝试在 ScreenD 中再次使用它,就会发生这种情况。
BlocProvider
,确保在离开ScreenA
导航时不会关闭或处置BlocB
实例。 这样,同一个BlocB
实例在整个导航堆栈中始终可用。BlocB
实例作为构造函数参数传递到下一个屏幕,而不是依赖BlocProvider.value
来重新创建它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.