繁体   English   中英

未处理的异常:错误 state:调用关闭后无法添加新事件 - 屏幕之间

[英]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 的屏幕

该错误消息表明在BlocListenerScreenF中使用的BlocB实例不再有效。 如果在离开ScreenA时关闭或处置BlocB实例,然后尝试在 ScreenD 中再次使用它,就会发生这种情况。

可能的解决方案:
  1. 通过使用位于整个导航堆栈之上而非仅位于各个屏幕内的BlocProvider ,确保在离开ScreenA导航时不会关闭或处置BlocB实例。 这样,同一个BlocB实例在整个导航堆栈中始终可用。
  2. BlocB实例作为构造函数参数传递到下一个屏幕,而不是依赖BlocProvider.value来重新创建它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM