Android implementation
- Flutter course
- Expert
- Lesson 18/39
- 4 min
Write plugin methods on the Android side.
Android implementation
On the Android side, a plugin is a Kotlin class implementing the FlutterPlugin interface. The onMethodCall method catches incoming MethodCalls from Dart and replies.
class MyPluginAndroid: FlutterPlugin, MethodCallHandler {
override fun onMethodCall(call: MethodCall, result: Result) {
if (call.method == "getVersion") {
result.success("1.0")
} else {
result.notImplemented()
}
}
}Kotlin and MethodCall
A plugin written in Kotlin implements the FlutterPlugin and MethodCallHandler interfaces. MethodCall.method gives the call name and MethodCall.argument gives the parameters. Result.success returns the reply to Dart.
Practice AndroidPlugin simulation
Define a Dart class named AndroidPlugin. Its onMethodCall(String method) method returns a String: '1.0' if method == 'getVersion', otherwise 'unknown'. In main, create an AndroidPlugin instance and print the result of onMethodCall('getVersion').
Starter code
// AndroidPlugin sınıfını tanımla
// onMethodCall metodu String alıp String döndürsün
// version çağrısı için 1.0, diğerleri için unknown döndürsün
void main() {
// AndroidPlugin örneği al ve version çağrısının sonucunu yazdır
}Sample solution
class AndroidPlugin {
String onMethodCall(String method) {
if (method == 'getVersion') {
return '1.0';
}
return 'unknown';
}
}
void main() {
final plugin = AndroidPlugin();
print(plugin.onMethodCall('getVersion'));
}Expected output
1.0
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which method catches calls from Dart on the Android side?
- build
- onCreate
- onMethodCall Correct answer
- onClick
Explanation: The onMethodCall method of the MethodCallHandler interface receives MethodCalls from Dart; build is for widgets, onCreate for activities, and onClick for view events.
2 result.success call
result.____("1.0");
result.success("1.0");
Explanation: result.success returns the reply to Dart; error takes 3 arguments for error cases, notImplemented takes no arguments, and complete is not a valid method on Result.
3 Android implementation matches
| Term | Meaning |
|---|---|
Android |
Mobile platform |
MethodCall |
Call from Dart |
Kotlin |
Android programming language |
onMethodCall |
Call capture |