单个属性
此Stream的单个元素。
如果此Stream发出错误事件,返回的Future将以该错误完成,并停止处理。
如果此Stream为空或包含多个元素,返回的Future将以错误完成。
实现
Future<T> get single {
_Future<T> future = new _Future<T>();
late T result;
bool foundResult = false;
StreamSubscription<T> subscription =
this.listen(null, onError: future._completeError, onDone: () {
if (foundResult) {
future._complete(result);
return;
}
try {
throw IterableElementError.noElement();
} catch (e, s) {
_completeWithErrorCallback(future, e, s);
}
}, cancelOnError: true);
subscription.onData((T value) {
if (foundResult) {
// This is the second element we get.
try {
throw IterableElementError.tooMany();
} catch (e, s) {
_cancelAndErrorWithReplacement(subscription, future, e, s);
}
return;
}
foundResult = true;
result = value;
});
return future;
}