call method

Future<R> call([
  1. List? positionalArguments,
  2. Map<Symbol, dynamic>? namedArguments
])

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

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;
}