Arron Murray
Arron Murray

Reputation: 193

How to listen on a future stream in Dart?

I am trying to listen to a future stream and I am running into an error. I have tried everything and yet the error returned is;

The method 'listen' isn't defined for the class 'Future'. Try correcting the name to the name of an existing method, or defining a method named 'listen'.dart(undefined_method)

How do I accomplish this?

Stream<AdventuresState> _mapLoadAdventureToState() async* {
    _adventureSubscription?.cancel();
    try {
      _adventureSubscription = _adventureRepository.getAdventures(_profileID).listen(
            (adventure) => add(
              AdventuresUpdated(adventure),
            ),
          );
    } catch (error) {
      AdventureError("Error: $error");
    }
}

Upvotes: 2

Views: 2590

Answers (2)

Steven Ogwal
Steven Ogwal

Reputation: 802

Receiving stream events as Future

The asynchronous for loop (commonly just called await for) iterates over the events of a stream like the for loop iterates over an Iterable.

Future<AdventuresState> _getSingleStep(Stream<AdventuresState> adventureStream) async {
    await for (var adventure in adventureStream) {
      return adventure;
    }
}

Source: https://dart.dev/tutorials/language/streams

Upvotes: 1

Frank Treacy
Frank Treacy

Reputation: 3716

Is something like this you want to do?

Stream<AdventuresState> _mapLoadAdventureToState() async* {
  final adventure = await _adventureRepository.getAdventures(_profileID);
  yield AdventuresUpdated(adventure);
}

Upvotes: 0

Related Questions