[英]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.