Flutter与原生代码交互教程
Flutter与原生代码交互教程
3 回复
推荐官方文档:https://flutter.dev/docs/development/platform-integration。通过Platform Channels实现交互。
更多关于Flutter与原生代码交互教程的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
推荐官方文档:使用平台通道与原生代码交互。简单易懂,适合初学者。
Flutter与原生代码交互主要通过平台通道(Platform Channel)实现。Flutter提供了MethodChannel
和EventChannel
两种方式来实现与原生代码的通信。
1. 使用MethodChannel
进行双向通信
MethodChannel
允许Flutter调用原生代码,并接收原生代码的返回值。
Flutter端代码
import 'package:flutter/services.dart';
class NativeBridge {
static const platform = MethodChannel('com.example.app/native');
Future<String> getNativeData() async {
try {
final String result = await platform.invokeMethod('getNativeData');
return result;
} on PlatformException catch (e) {
return "Failed to get native data: '${e.message}'.";
}
}
}
Android端代码
在MainActivity.kt
中:
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
class MainActivity: FlutterActivity() {
private val CHANNEL = "com.example.app/native"
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler { call, result ->
if (call.method == "getNativeData") {
result.success("Hello from Android")
} else {
result.notImplemented()
}
}
}
}
iOS端代码
在AppDelegate.swift
中:
import UIKit
import Flutter
@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
let controller : FlutterViewController = window?.rootViewController as! FlutterViewController
let nativeChannel = FlutterMethodChannel(name: "com.example.app/native",
binaryMessenger: controller.binaryMessenger)
nativeChannel.setMethodCallHandler({
(call: FlutterMethodCall, result: @escaping FlutterResult) -> Void in
if call.method == "getNativeData" {
result("Hello from iOS")
} else {
result(FlutterMethodNotImplemented)
}
})
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}
2. 使用EventChannel
进行流式通信
EventChannel
用于从原生代码向Flutter发送连续的事件流。
Flutter端代码
import 'package:flutter/services.dart';
class NativeEventStream {
static const eventChannel = EventChannel('com.example.app/events');
Stream<String> get nativeEventStream {
return eventChannel.receiveBroadcastStream().map((event) => event.toString());
}
}
Android端代码
在MainActivity.kt
中:
import io.flutter.plugin.common.EventChannel
class MainActivity: FlutterActivity() {
private val EVENT_CHANNEL = "com.example.app/events"
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
EventChannel(flutterEngine.dartExecutor.binaryMessenger, EVENT_CHANNEL).setStreamHandler(
object : EventChannel.StreamHandler {
override fun onListen(arguments: Any?, events: EventChannel.EventSink) {
events.success("Event from Android")
}
override fun onCancel(arguments: Any?) {
// Clean up resources if needed
}
}
)
}
}
iOS端代码
在AppDelegate.swift
中:
import UIKit
import Flutter
@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
let controller : FlutterViewController = window?.rootViewController as! FlutterViewController
let eventChannel = FlutterEventChannel(name: "com.example.app/events",
binaryMessenger: controller.binaryMessenger)
eventChannel.setStreamHandler(EventStreamHandler())
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}
class EventStreamHandler: NSObject, FlutterStreamHandler {
func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? {
events("Event from iOS")
return nil
}
func onCancel(withArguments arguments: Any?) -> FlutterError? {
return nil
}
}
总结
通过MethodChannel
和EventChannel
,Flutter可以方便地与原生代码进行交互。MethodChannel
适用于一次性调用,而EventChannel
适用于流式数据传输。根据需求选择合适的通道类型即可。