如何在回调函数中产生?

How to yield inside callback function?

请阅读此 bloc 片段:

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();

但我很好奇。

您已经介绍了最好的方法,原因如下:

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

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


Return 来自回调

在处理 Future 时,您还可以 return 您在回调中的值,如下所示:

yield 1;

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