Method Channels in Flutter
What are Method Channels in Flutter?
1.Channel Definition:
2.Method Invocation:
3.Data Exchange:
4.Result Handling:
领英推荐
Example:
Dart
import 'package:flutter/services.dart';
class MyPlugin {
static const platform = MethodChannel('com.example.my_app/my_channel');
static Future<String?> getPlatformVersion() async {
try {
final String? version = await platform.invokeMethod('getPlatformVersion');
return version;
} on PlatformException catch (e) {
return 'Failed to get platform version.';
}
}
}
Native Code (Android - Kotlin):
Kotlin
import androidx.annotation.NonNull;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;
class MyPlugin: MethodCallHandler {
private val channel: MethodChannel
constructor(flutterEngine: FlutterEngine) {
channel = MethodChannel(flutterEngine.dartExecutor, "com.example.my_app/my_channel")
channel.setMethodCallHandler(this)
}
override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {
if (call.method == "getPlatformVersion") {
result.success("Android ${android.os.Build.VERSION.release}")
} else {
result.notImplemented()
}
}
}
iOS (Swift):
Swift
import Flutter
public class SwiftMethodHandler: NSObject, FlutterPlugin {
public static func register(with registrar: FlutterPluginRegistrar) {
let channel = FlutterMethodChannel(name: "com.example.my_app/my_channel", binaryMessenger: registrar.messenger())
let instance = SwiftMethodHandler()
registrar.addMethodCallDelegate(instance, channel: channel)
}
public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
if (call.method == "getPlatformVersion") {
result("iOS " + UIDevice.current.systemVersion)
} else {
result(FlutterMethodNotImplemented)
}
}
}
Key Benefits of Method Channels:
By effectively using Method Channels, you can create powerful and flexible Flutter applications that seamlessly integrate with the underlying native platforms.