invokeMethod
- Flutter course
- Advanced
- Lesson 47/69
- 4 min
Call native methods with invokeMethod.
The invokeMethod method
invokeMethod sends a method call from Dart to the native side. The first parameter is the method name, and the native side performs its operation with this name. The method is asynchronous, so you await it with await, and the returned value comes from the native side.
final result = await channel.invokeMethod('getBatteryLevel');Passing arguments
To send arguments to a native method, the second parameter of invokeMethod is used. Arguments are passed as a Map, and the native side accesses values through these keys. Types are automatically converted between Dart and native.
final result = await channel.invokeMethod(
'getBatteryLevel',
{'deviceId': 'phone1'},
);Practice Call a native method and print it
Create a MethodChannel, await the battery level method with invokeMethod and print the result.
Starter code
class MethodChannel {
final String name;
MethodChannel(this.name);
Future<int> invokeMethod(String method, [Map<String, dynamic>? args]) async => 80;
}
void main() async {
// invokeMethod ile pil seviyesi metodunu çağır
// sonucu yazdır
}Sample solution
class MethodChannel {
final String name;
MethodChannel(this.name);
Future<int> invokeMethod(String method, [Map<String, dynamic>? args]) async => 80;
}
void main() async {
const channel = MethodChannel('samples.flutter.dev/battery');
final result = await channel.invokeMethod('getBatteryLevel');
print(result);
}Expected output
80
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does the first parameter of invokeMethod specify?
- The channel name
- The error code
- The return type
- The method name to call on the native side Correct answer
Explanation: The first parameter of invokeMethod is the method name to call on the native side; the channel name is given when creating the MethodChannel.
2 Call a native method
final result = await channel.____('getBatteryLevel');
final result = await channel.invokeMethod('getBatteryLevel');
Explanation: To call a native method you use invokeMethod; the first parameter is the method name and it is awaited.
3 invokeMethod parts
| Term | Meaning |
|---|---|
invokeMethod |
Calls a native method |
await |
Awaits asynchronously |
'getBatteryLevel' |
Method name |
Map |
Argument container |