在混乱中,我们利用StreamBuilder接收Stream e,这使我们获得了一个包含“数据”但也包含“错误”对象的Snapshot对象。
我想用async *创建一个函数,该函数可以产生数据,但是由于某些条件,它还可以产生一些错误。如何在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中:
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!
},
)
答案 0 :(得分:4)
简单地扔
Stream<int> foo() async* {
throw FormatException();
}
答案 1 :(得分:0)
在工作示例下方:
void main() {
justAFunction().listen((i) => print(i), onError: (error) => print(error));
}
Stream<int> justAFunction() async* {
yield 0;
for (var i = 1; i < 3; ++i) {
await Future.delayed(Duration(milliseconds:500));
yield i;
}
yield* Stream.error('error is here'); <- Yield error!
}