elementAt method

Future<T> elementAt(int index)

Returns the value of the indexth data event of this stream.

Stops listening to the stream after the indexth data event has been received.

Internally the method cancels its subscription after these elements. This means that single-subscription (non-broadcast) streams are closed and cannot be reused after a call to this method.

If an error event occurs before the value is found, the future completes with this error.

If a done event occurs before the value is found, the future completes with a RangeError.

Source

Future<T> elementAt(int index) {
  if (index is! int || index < 0) throw new ArgumentError(index);
  _Future<T> future = new _Future<T>();
  StreamSubscription subscription;
  int elementIndex = 0;
  subscription = this.listen(
      (T value) {
        if (index == elementIndex) {
          _cancelAndValue(subscription, future, value);
          return;
        }
        elementIndex += 1;
      },
      onError: future._completeError,
      onDone: () {
        future._completeError(
            new RangeError.index(index, this, "index", null, elementIndex));
      },
      cancelOnError: true);
  return future;
}

© 2012 the Dart project authors
Licensed under the Creative Commons Attribution-ShareAlike License v4.0.
https://api.dartlang.org/stable/1.24.3/dart-async/Stream/elementAt.html