如何通过Dart中的async *传输错误? [英] How to transmit an error through async* in Dart?

查看:77
本文介绍了如何通过Dart中的async *传输错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在混乱中,我们利用StreamBuilder接收Stream e,这为我们提供了一个包含数据但也包含错误对象的Snapshot对象。

In flutter we make use of the StreamBuilder with receives a Stream e gives us a Snapshot object that contains "data" but also contains "error" objects.

I想要使用async *函数来产生数据,但是由于某些条件,它可能也会产生一些错误。如何在Dart中实现?

I want to make a function with async* that yields data but due to some conditions it can yield also some errors. How can I achieve that in Dart?

Stream<int> justAFunction() async* {
  yield 0;

  for (var i = 1; i < 11; ++i) {
    await Future.delayed(millis(500));
    yield i;
  }

  yield AnyError(); <- I WANT TO YIELD THIS!
}

然后在StreamBuilder中:

And then, in the StreamBuilder:

StreamBuilder(
            stream: justAFunction(),
            builder: (BuildContext context, AsyncSnapshot<RequestResult> snapshot) {
              return Center(child: Text("The error tha came: ${snapshot.error}")); <- THIS SHOULD BE THE AnyError ABOVE!
            },
          )


推荐答案

简单抛出

Stream<int> foo() async* {
  throw FormatException();
}

这篇关于如何通过Dart中的async *传输错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆