簡體   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