invokeNativeMethodSafe static method

Future invokeNativeMethodSafe(
  1. String method, {
  2. Map<String, dynamic>? arguments,
  3. Duration timeout = const Duration(seconds: 30),
  4. void onError(
    1. OsmosException
    )?,
})

Safe version that returns null on error instead of throwing.

  • method: The name of the native method to invoke.
  • arguments: The arguments to pass to the native method (optional).
  • timeout: Maximum time to wait for the method call (default: 30 seconds).
  • onError: Optional error callback function.
  • Returns: A Future with the result or null if error occurs.

Implementation

static Future<dynamic> invokeNativeMethodSafe(
  String method, {
  Map<String, dynamic>? arguments,
  Duration timeout = const Duration(seconds: 30),
  void Function(OsmosException)? onError,
}) async {
  try {
    return await _channel.invokeMethod(method, arguments).timeout(
          timeout,
          onTimeout: () => throw OsmosException.fromPlatformException(
            PlatformException(
              code: OsmosErrorCodes.timeoutError.code,
              message:
                  'Method call timed out after ${timeout.inSeconds} seconds',
              details: 'Method: $method',
            ),
          ),
        );
  } catch (error) {
    final osmosException = OsmosException.fromError(error);
    if (onError != null) {
      onError(osmosException);
    } else {
      debugPrint('Osmos Plugin Error: ${osmosException.toString()}');
    }
    return null;
  }
}