MethodChannel registration
- Flutter course
- Expert
- Lesson 17/39
- 4 min
Register the plugin's MethodChannel.
MethodChannel registration
A plugin starts on the Dart side with a registerWith method. It creates a MethodChannel and captures incoming native calls with setMethodCallHandler. The plugin is registered automatically when the app launches.
class MyPlugin {
static const _channel = MethodChannel('my_plugin');
static void registerWith() {
_channel.setMethodCallHandler(_handle);
}
static Future<dynamic> _handle(MethodCall call) async {
return 'ok';
}
}setMethodCallHandler
setMethodCallHandler catches incoming MethodCall messages from native. The handler branches on the call's method name and returns a result. This is the plugin's Dart-native bridge.
Practice Define a plugin with registerWith
Define MyPlugin: static const _channel = MethodChannel('my_plugin'), a static void registerWith() method that calls _channel.setMethodCallHandler(_handle), and a static Future<dynamic> _handle(MethodCall call) async => 'ok'. In main, print 'kaydedildi'.
Starter code
import 'package:flutter/services.dart';
// MyPlugin sınıfını tanımla
// 'my_plugin' adlı bir MethodChannel static const ata
// kayıt metodu handler ataması yapsın
// çağrı işleyici metodu 'ok' döndürsün
void main() {
// 'kaydedildi' yazdır
}Sample solution
import 'package:flutter/services.dart';
class MyPlugin {
static const _channel = MethodChannel('my_plugin');
static void registerWith() {
_channel.setMethodCallHandler(_handle);
}
static Future<dynamic> _handle(MethodCall call) async => 'ok';
}
void main() {
print('kaydedildi');
}Expected output
kaydedildi
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does the registerWith method do?
- Opens a database
- Starts the app
- Draws the widget tree
- Creates a MethodChannel and registers a call listener Correct answer
Explanation: registerWith sets up the MethodChannel and assigns the handler that listens to incoming native calls via setMethodCallHandler.
2 setMethodCallHandler call
_channel.____(_handle);
_channel.setMethodCallHandler(_handle);
Explanation: setMethodCallHandler assigns the handler that catches MethodCalls; invokeMethod calls from Dart to native, setMessageHandler is lower-level, and listen is for streams.
3 MethodChannel registration matches
| Term | Meaning |
|---|---|
registerWith |
Plugin registration |
MethodChannel |
Call channel |
plugin |
Native-bridged package |
setMethodCallHandler |
Call listener |