call method
Call the closure, which was provided as an argument to the CallOnce constructor, with the specified arguments.
Returns the result of calling _closure
. The result is cached,
so any subsequent calls return the cached result.
Errors
-
Throws a CallOnceInvalidArgumentsError if the provided arguments do not match the signature of
_closure
. -
Throws a CallOnceClosureResultError if the result returned by
_closure
is not of typeR
orFuture<R>
.
Implementation
Future<R> call([
List<dynamic>? positionalArguments,
Map<Symbol, dynamic>? namedArguments,
]) async {
if (_wasCalled) return _completer.future;
_wasCalled = true;
final dynamic closureResult;
try {
closureResult = Function.apply(
_closure,
positionalArguments,
namedArguments,
);
// [NoSuchMethodError] must be converted to a
// [CallOnceInvalidArgumentsError].
// ignore: avoid_catching_errors
} on NoSuchMethodError catch (_) {
throw CallOnceInvalidArgumentsError._(
_closure,
positionalArguments,
namedArguments,
);
}
// Ensure that closureResult is either R or Future<R>
if (closureResult is! R && closureResult is! Future<R>) {
throw CallOnceClosureResultError<R>._(
closure: _closure,
namedArguments: namedArguments,
positionalArguments: positionalArguments,
result: closureResult,
);
}
final R res = await closureResult;
_completer.complete(res);
return res;
}