Sub topic 6
Calling Native Methods from Dart
This chapter assumes intermediate Dart, Flutter asynchronous programming, and a native handler already registered on Android or iOS. You will learn how Dart sends one request and receives one response through a MethodChannel.
How a Method Call Works
A MethodChannel is a named communication path between Dart and native code. Both sides must use exactly the same channel name. Dart sends a method name and optional arguments. The native handler processes the request and completes it with a success value, an error, or “not implemented.”
Invoking a Native Method
Use invokeMethod to send a request. Its first argument is the method name. Its optional second argument contains values that the channel codec can encode, such as strings, numbers, booleans, lists, and maps.
The generic type <String> tells Dart what result type you expect. The returned Future completes when native code sends a response.
import 'package:flutter/services.dart';
class GreetingApi {
static const _channel = MethodChannel('com.example.app/greeting');
Future<String> greet(String name) async {
final result = await _channel.invokeMethod<String>('greet', {
'name': name,
});
return result ?? '';
}
}A widget or service can call the wrapper like this:
final greetingApi = GreetingApi();
Future<void> loadGreeting() async {
final message = await greetingApi.greet('Mina');
print(message);
}Keep channel calls behind a Dart wrapper. The rest of the application then depends on GreetingApi, rather than on channel names and untyped maps.
Handling Results and Failures
The native side must complete every call. A successful response becomes the value returned by invokeMethod. If native code reports an error, Dart throws a PlatformException. If no native implementation exists, Dart can throw a MissingPluginException.
Future<void> loadGreetingSafely() async {
try {
final message = await GreetingApi().greet('Mina');
print(message);
} on PlatformException catch (error) {
print('Native error ${error.code}: ${error.message}');
} on MissingPluginException {
print('The greeting method is unavailable on this platform.');
}
}A nullable result is valid. For example, native code may return null when no value exists. Decide whether that means an empty value, a missing value, or an application error. Do not silently hide errors by converting every failure into an empty string.
Exercise
What happens if Dart invokes greet with a map containing user instead of name?
Show answer
The native handler may treat name as missing and return an argument error. Dart receives that failure as a PlatformException.