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!
},
)
What is the difference between async and async* in Dart? The difference between both is that async* will always return a Stream and offer some syntax sugar to emit a value through the yield keyword. async gives you a Future and async* gives you a Stream.
async: You can use the async keyword before a function's body to mark it as asynchronous. async function: An async function is a function labeled with the async keyword. await: You can use the await keyword to get the completed result of an asynchronous expression. The await keyword only works within an async function.
The throw keyword is used to explicitly raise an exception. A raised exception should be handled to prevent the program from exiting abruptly.
The try block contains the code that might possibly throw an exception. The try block must be followed by on or catch blocks, and an optional finally block. The catch block is used to catch and handle any exceptions thrown in the try block. To catch specific exceptions, the on keyword can be used instead of catch .
Simply throw
Stream<int> foo() async* {
throw FormatException();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With