【问题标题】:How to yield inside callback function?如何产生内部回调函数?
【发布时间】:2026-02-21 22:30:01
【问题描述】:

请阅读这个集团片段:

if (event is TapVariant) {
  final bool isVariantCorrect = (correctVariantIndex == event.index);
  if (isVariantCorrect) {  
    yield CorrectVariant();
  } else {
    yield IncorrectVariant();
    Future.delayed(Duration(seconds: 1), () { 
      yield CorrectVariant();
    });
  }
}

我需要从嵌套函数中生成 CorrectVariant。

我是这样解决的:

    yield IncorrectVariant();
    await Future.delayed(Duration(seconds: 1), () {});
    yield CorrectVariant();

但我很好奇。

【问题讨论】:

    标签: flutter dart bloc


    【解决方案1】:

    您已经提出了最好的方法,原因如下:

    • 当您在 async* 函数中时,您可以访问 await 关键字,它允许您在同一范围内处理未来的回调。

    • 如果您在 sync* 函数中使用 yield,则无论如何您都无法等待回调,因为您没有运行异步代码。


    从回调中返回

    当您处理Future 时,您还可以像这样在回调中返回您的值:

    yield 1;
    
    // The following statement will yield "2" after one second.
    yield await Future.delayed(Duration(seconds: 1), () {
      return 2;
    });
    

    【讨论】: