flutter runtime_error ai_generated true

状态错误:在添加另一个事件时无法添加事件

StateError: Bad state: Cannot add event while adding another event

ID: flutter/state-error-bloc-event-handler

其他格式: JSON · Markdown 中文 · English
88%修复率
88%置信度
1证据数
2023-11-15首次发现

版本兼容性

版本状态引入弃用备注
flutter 3.16 active
flutter 3.22 active
bloc 8.0.0 active
flutter_bloc 8.1.0 active

根因分析

在同一个 Bloc 实例的事件处理程序中调用 bloc.add(),导致重入调用。

English

Attempting to call bloc.add() from within an event handler of the same Bloc instance, causing a reentrant call.

generic

官方文档

https://bloclibrary.dev/#/coreconcepts?id=adding-events

解决方案

  1. 使用单独的隔离或通过 Future.microtask(() => bloc.add(Event())) 在当前处理程序外部调度新事件。这确保当前事件处理完成后再添加新事件。
  2. 重构 Bloc 逻辑,将两个操作合并为一个事件,或在使用 bloc.add() 之前使用异步间隙,如 await Future.delayed(Duration.zero)。

无效尝试

常见但无效的做法:

  1. Adding a short delay with Future.delayed before bloc.add() 85% 失败

    Delay does not prevent the reentrant call from the same synchronous context; the error still occurs if the logic is in the same event handler chain.

  2. Wrapping bloc.add() in a try-catch block 75% 失败

    The StateError is thrown synchronously and cannot be caught inside the event handler because Bloc internally throws it before the catch block is reached.