DEV Community

oganao
oganao

Posted on

A compile error of await for in Dart

People love dart programming language because of its easy-to-use asynchronous feature. I definitely agree with it.

I came across the following error the other day.

The type 'Stream' used in the 'for' loop must implement Iterable. (view docs)

My code snippest was :

void main() async {

  for(String v in countStream('a b c d')) { // *** compile error ***
    print(v);
  };

 }

Stream<String> countStream(String text) async* {
  var words = text.split(' ');
  for (int i = 0; i <= words.length; i++) {
    await Future.delayed(const Duration(milliseconds: 300));
    yield words.getRange(0, i).join(' ');
  }
}
Enter fullscreen mode Exit fullscreen mode

You'll soon notice I forgot "await" before "for". But I couldn't figure out that. I went the wrong way.

The compiler requested Iterable, so I was wondering if Stream is Iterable and googled how to make Stream into Iterable. It was a wast of time.

In dart, "await for" is said to be "Asynchronous For-in" in the language specification. It is different from "for", which is used for asynchronous.

The compiler can't infer which feature a programmer intends to use, even thought one codes async*.

Top comments (0)