Reputation: 8953
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 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!
}
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!
},
)
Upvotes: 9
Views: 1759
Reputation: 7100
Below the working example:
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!
}
Upvotes: 3
Reputation: 276997
Simply throw
Stream<int> foo() async* {
throw FormatException();
}
Upvotes: 12