invokeNativeMethod method

Future<Either<String, dynamic>> invokeNativeMethod(
  1. String methodName, [
  2. dynamic arguments
])

Invokes a native method through the method channel and handles the response.

This method attempts to call a native method specified by methodName with optional arguments. It returns a Future that resolves to an Either type, where the left side contains an error message and the right side contains the successful response.

The method handles various exceptions:

  • PlatformException: Logs the error and returns the error message.
  • MissingPluginException: Logs that the method is not implemented and returns a default error message.
  • Any other exceptions: Logs the unexpected error and returns a default error message.

Returns:

  • Left(String): If there is an error or the native method indicates failure.
  • Right(dynamic): If the native method call is successful.

Implementation

Future<Either<String, dynamic>> invokeNativeMethod(
  String methodName, [
  dynamic arguments,
]) async {
  try {
    final result = await methodChannel.invokeMethod(methodName, arguments);
    if (result['success'] == false) {
      return Left(
        result['message'],
      );
    }
    return Right(result['response']);
  } on PlatformException catch (e) {
    log('Error from native: ${e.code} - ${e.message} -> $methodName ($arguments)');
    return Left(e.message ?? 'Error from native');
  } on MissingPluginException {
    log('Native method not implemented: $methodName');
    return const Left('Method not implemented');
  } catch (e) {
    log('Unexpected error: $e');
    return const Left('Unexpected error');
  }
}