W3cubDocs

/Dart 2

elementAt method

Future<T> elementAt (int index)

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

Stops listening to this 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.

Implementation

Future<T> elementAt(int index) {
  ArgumentError.checkNotNull(index, "index");
  RangeError.checkNotNegative(index, "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.dart.dev/stable/2.5.0/dart-async/Stream/elementAt.html