contains方法

Future<bool> contains(
  1. Object? needle
)

返回此流提供的元素中是否包含needle

使用Object.==将此流的每个元素与needle进行比较。如果找到相等的元素,则返回的future完成为true。如果此流结束且未找到匹配项,则future完成为false

如果此流发出错误,或调用Object.==抛出异常,则返回的future完成为此错误,并且处理停止。

示例

final result = await Stream.fromIterable(['Year', 2021, 12, 24, 'Dart'])
    .contains('Dart');
print(result); // true

实现

Future<bool> contains(Object? needle) {
  _Future<bool> future = new _Future<bool>();
  StreamSubscription<T> subscription =
      this.listen(null, onError: future._completeError, onDone: () {
    future._complete(false);
  }, cancelOnError: true);
  subscription.onData((T element) {
    _runUserCode(() => (element == needle), (bool isMatch) {
      if (isMatch) {
        _cancelAndValue(subscription, future, true);
      }
    }, _cancelAndErrorClosure(subscription, future));
  });
  return future;
}