Flutter 混合開發系列 包含以下:java
- 嵌入原生View-Android
- 嵌入原生View-iOS
- 與原生通訊-MethodChannel
- 與原生通訊-BasicMessageChannel
- 與原生通訊-EventChannel
- 添加 Flutter 到 Android Activity
- 添加 Flutter 到 Android Fragment
- 添加 Flutter 到 iOS
每一個工做日分享一篇,歡迎關注、點贊及轉發。android
Flutter 與 Native 端通訊有以下3個方法:ios
此圖爲官方的架構圖git
Flutter 與 Native 端通訊是異步的。swift
Native 端主動發送數據給 Flutter時,Native 端代碼須要在主線程中執行,Android 端從子線程跳轉到主線程方式:api
Kotlin 代碼:微信
Handler(Looper.getMainLooper()).post { }
Java 代碼:網絡
new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { } });
若是能夠獲取到當前 Activity,也能夠使用以下方式:架構
activity.runOnUiThread { }
iOS 端從子線程跳轉到主線程方式:app
Objective-C 代碼:
dispatch_async(dispatch_get_main_queue(), ^{ });
Swift 代碼:
DispatchQueue.main.async { }
Flutter 端建立 MethodChannel 通道,用於與原生端通訊:
var channel = MethodChannel('com.flutter.guide.MethodChannel');
com.flutter.guide.MethodChannel 是 MethodChannel 的名稱,原生端要與之對應。
發送消息:
var result = await channel.invokeMethod('sendData',{'name': 'laomeng', 'age': 18})
完整代碼:
class MethodChannelDemo extends StatefulWidget { @override _MethodChannelDemoState createState() => _MethodChannelDemoState(); } class _MethodChannelDemoState extends State<MethodChannelDemo> { var channel = MethodChannel('com.flutter.guide.MethodChannel'); var _data; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(), body: Column( children: [ SizedBox( height: 50, ), RaisedButton( child: Text('發送數據到原生'), onPressed: () async { var result = await channel .invokeMethod('sendData', {'name': 'laomeng', 'age': 18}); var name = result['name']; var age = result['age']; setState(() { _data = '$name,$age'; }); }, ), Text('原生返回數據:$_data') ], ), ); } }
android 下建立 MethodChannelDemo:
package com.flutter.guide import io.flutter.plugin.common.BinaryMessenger import io.flutter.plugin.common.MethodCall import io.flutter.plugin.common.MethodChannel /** * des: */ class MethodChannelDemo(messenger: BinaryMessenger): MethodChannel.MethodCallHandler { private var channel: MethodChannel init { channel = MethodChannel(messenger, "com.flutter.guide.MethodChannel") channel.setMethodCallHandler(this) } override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) { } }
onMethodCall 方法在 Flutter 端調用 invokeMethod 方法回調,解析方法以下:
override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) { if (call.method == "sendData") { val name = call.argument("name") as String? val age = call.argument("age") as Int? var map = mapOf("name" to "hello,$name", "age" to "$age" ) result.success(map) } }
Flutter 端解析:
var result = await channel .invokeMethod('sendData', {'name': 'laomeng', 'age': 18}); var name = result['name']; var age = result['age'];
兩端的解析要相互對應。
在 MainActivity 啓動:
class MainActivity : FlutterActivity() { override fun configureFlutterEngine(flutterEngine: FlutterEngine) { super.configureFlutterEngine(flutterEngine) MethodChannelDemo(flutterEngine.dartExecutor.binaryMessenger) } }
ios 下建立 MethodChannelDemo,按以下方式:
import Flutter import UIKit public class MethodChannelDemo { init(messenger: FlutterBinaryMessenger) { let channel = FlutterMethodChannel(name: "com.flutter.guide.MethodChannel", binaryMessenger: messenger) channel.setMethodCallHandler { (call:FlutterMethodCall, result:@escaping FlutterResult) in if (call.method == "sendData") { if let dict = call.arguments as? Dictionary<String, Any> { let name:String = dict["name"] as? String ?? "" let age:Int = dict["age"] as? Int ?? -1 result(["name":"hello,\(name)","age":age]) } } } } }
在 AppDelegate 啓動:
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 MethodChannelDemo(messenger: controller.binaryMessenger) GeneratedPluginRegistrant.register(with: self) return super.application(application, didFinishLaunchingWithOptions: launchOptions) } }
@override void initState() { super.initState(); channel.setMethodCallHandler((call) { setState(() { _nativeData = call.arguments['count']; }); }); }
原生端啓動定時器,每隔一秒向 Flutter 發送數據,Android 端代碼:
class MethodChannelDemo(var activity: Activity, messenger: BinaryMessenger) : MethodChannel.MethodCallHandler { private var channel: MethodChannel private var count = 0 init { channel = MethodChannel(messenger, "com.flutter.guide.MethodChannel") channel.setMethodCallHandler(this) startTimer() } fun startTimer() { var timer = Timer().schedule(timerTask { activity.runOnUiThread { var map = mapOf("count" to count++) channel.invokeMethod("timer", map) } }, 0, 1000) } override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) { if (call.method == "sendData") { val name = call.argument("name") as String? val age = call.argument("age") as Int? var map = mapOf("name" to "hello,$name", "age" to "$age" ) result.success(map) } } }
注意:Android 端發送數據要在主現場中調用,即:
activity.runOnUiThread { var map = mapOf("count" to count++) channel.invokeMethod("timer", map) }
啓動修改以下:
class MainActivity : FlutterActivity() { override fun configureFlutterEngine(flutterEngine: FlutterEngine) { super.configureFlutterEngine(flutterEngine) MethodChannelDemo(this,flutterEngine.dartExecutor.binaryMessenger) flutterEngine.plugins.add(MyPlugin()) } }
iOS 端啓動定時器代碼以下:
import Flutter import UIKit public class MethodChannelDemo { var count = 0 var channel:FlutterMethodChannel init(messenger: FlutterBinaryMessenger) { channel = FlutterMethodChannel(name: "com.flutter.guide.MethodChannel", binaryMessenger: messenger) channel.setMethodCallHandler { (call:FlutterMethodCall, result:@escaping FlutterResult) in if (call.method == "sendData") { if let dict = call.arguments as? Dictionary<String, Any> { let name:String = dict["name"] as? String ?? "" let age:Int = dict["age"] as? Int ?? -1 result(["name":"hello,\(name)","age":age]) } } } startTimer() } func startTimer() { var timer = Timer.scheduledTimer(timeInterval:1, target: self, selector:#selector(self.tickDown),userInfo:nil,repeats: true) } @objc func tickDown(){ count += 1 var args = ["count":count] channel.invokeMethod("timer", arguments:args) } }
老孟Flutter博客(330個控件用法+實戰入門系列文章):http://laomengit.com
歡迎加入Flutter交流羣(微信:laomengit)、關注公衆號【老孟Flutter】: