Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to transmit an error through async* in Dart?

Tags:

flutter

dart

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!
            },
          )
like image 754
Daniel Oliveira Avatar asked Feb 18 '19 22:02

Daniel Oliveira


People also ask

What's the difference between async and async * in Dart?

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.

How do you use async in Dart?

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.

How do you throw a Dart error?

The throw keyword is used to explicitly raise an exception. A raised exception should be handled to prevent the program from exiting abruptly.

How do you throw an error in Flutter?

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 .


1 Answers

Simply throw

Stream<int> foo() async* {
  throw FormatException();
}
like image 172
Rémi Rousselet Avatar answered Sep 28 '22 22:09

Rémi Rousselet