混合開發一般分2種
-
Flutter調用原生項目代碼(
MethodChannel
、BasicMessageChannel
、EventChannel
)- MethodChannel
實現Flutter與原生雙向發送消息
- BasicMessageChannel
實現Flutter與原生雙向發送數據
- EventChannel
實現原生向Flutter發送消息
- 當多個相同name的Channel綁定時,只有最后那個能收到消息。(只能1對1,與底層有關系,
c++源碼為一個字典存儲,字典的name為Channel的name,value為執行的閉包(這里的hander),因此最后由name查到一個閉包執行,誰最后添加誰就是那個閉包
)
- MethodChannel
-
原生項目使用Flutter項目功能(
Module
),這里只介紹iOS相關邏輯
一.MethodChannel
1.相關Api
1.構造方法
/// Creates a [MethodChannel] with the specified [name].
///
/// The [codec] used will be [StandardMethodCodec], unless otherwise
/// specified.
///
/// The [name] and [codec] arguments cannot be null. The default [ServicesBinding.defaultBinaryMessenger]
/// instance is used if [binaryMessenger] is null.
const MethodChannel(this.name, [this.codec = const StandardMethodCodec(), BinaryMessenger? binaryMessenger ])
: assert(name != null),
assert(codec != null),
_binaryMessenger = binaryMessenger;
-
name
當前MethodChannel的名稱,與原生的對應
2.發送數據
Future<T?> invokeMethod<T>(String method, [ dynamic arguments ]) {
return _invokeMethod<T>(method, missingOk: false, arguments: arguments);
}
-
invokeMethod
發送消息 -
method
消息名 -
dynamic
參數
3.接收數據
void setMethodCallHandler(Future<dynamic> Function(MethodCall call)? handler) {
binaryMessenger.setMessageHandler(
name,
handler == null
? null
: (ByteData? message) => _handleAsMethodCall(message, handler),
);
}
- 當執行了
invoke
的回調 - 必須返回一個Future
-
MethodCall
回調數據,包括method、arguments等信息
2.使用MethodChannel調起系統相冊
- iOS端代碼
@interface AppDelegate()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (nonatomic, strong) FlutterMethodChannel *channel;
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[GeneratedPluginRegistrant registerWithRegistry:self];
// Override point for customization after application launch.
FlutterViewController *flutterVc = (FlutterViewController *)self.window.rootViewController;
self.channel = [FlutterMethodChannel methodChannelWithName:@"picker_images" binaryMessenger:flutterVc.binaryMessenger];
UIImagePickerController *pickerVc = [[UIImagePickerController alloc] init];
pickerVc.delegate = self;
[self.channel setMethodCallHandler:^(FlutterMethodCall * _Nonnull call, FlutterResult _Nonnull result) {
if ([call.method isEqualToString:@"select_image"]) {
NSLog(@"選擇圖片");
[flutterVc presentViewController:pickerVc animated:true completion:nil];
}
}];
return [super application:application didFinishLaunchingWithOptions:launchOptions];
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info {
NSLog(@"%@", info);
[picker dismissViewControllerAnimated:true completion:^{
NSString * imagePath = [NSString stringWithFormat:@"%@",info[@"UIImagePickerControllerImageURL"]];
[self.channel invokeMethod:@"imagePath" arguments:imagePath];
}];
}
@end
-
FlutterMethodChannel
對應MethodChannel(Flutter) -
FlutterViewController
對應的Flutter渲染引擎控制器(在原生上只有一個控制器)
- Flutter端代碼(只貼出關鍵代碼)
class _MineHeaderState extends State<MineHeader> {
final MethodChannel _methodChannel = MethodChannel('picker_images');
File? _avatarFile;
@override
void initState() {
// TODO: implement initState
super.initState();
//選擇圖片后的回調
_methodChannel.setMethodCallHandler((call) {
if (call.method == 'imagePath') {
String imagePath = (call.arguments as String).substring(7);
print(imagePath);
setState(() {});
_avatarFile = File(imagePath);
}
return Future((){});
});
}
@override
Widget build(BuildContext context) {
return Container(
height: 260,
color: Colors.white,
child: Container(
// color: Colors.red,
margin: EdgeInsets.only(top: 150,left: 25, bottom: 25, right: 25),
child: Container(
child: Row(
children: [
GestureDetector(
onTap: () {
//發送消息給原生
_methodChannel.invokeMethod('select_image');
},
child: Container(
width: 80,
height: 80,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(12),
image: DecorationImage(
image: _avatarFile != null ? FileImage(_avatarFile!) as ImageProvider : AssetImage('images/stitch_icon.JPG'),
fit: BoxFit.cover)
),
),
),
Expanded(child: Container(
// color: Colors.white,
margin: EdgeInsets.only(left: 20, right: 20),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
child: Text('Stitch', style: TextStyle(fontSize: 16, fontWeight: FontWeight.w500)),
),
Container(
// color: Colors.yellow,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text('Stitch的個性簽名', style: TextStyle(fontSize: 14)),
Image.asset('images/icon_right.png', width: 15,)
],
),
)
],
),
))
],
),
),
),
);
}
}
methodChannel_ImagePicker.gif
2.使用image_picker調用系統相冊
- image_picker官方的選擇圖片插件
- 不用單獨去實現iOS/Android代碼
File? _avatarFile;
_pickerImage() {
ImagePicker().pickImage(source: ImageSource.gallery).then((value) {
if (value != null) {
setState(() {
_avatarFile = File(value.path);
});
}
}, onError: (e) {
print(e);
setState(() {
_avatarFile = null;
});
});
}
- 當然這里也可以使用異步任務,但是
必須要使用async和await
_asyncPickerImage() async {
try {
var xFile = await ImagePicker().pickImage(source: ImageSource.gallery);
if (xFile != null) {
_avatarFile = File(xFile.path);
}
setState(() {});
} catch (e) {
print(e);
setState(() {
_avatarFile = null;
});
}
}
二.BasicMessageChannel
- 使用與
MethodChannel
類似
1.相關Api
1.構造方法
/// Creates a [BasicMessageChannel] with the specified [name], [codec] and [binaryMessenger].
///
/// The [name] and [codec] arguments cannot be null. The default [ServicesBinding.defaultBinaryMessenger]
/// instance is used if [binaryMessenger] is null.
const BasicMessageChannel(this.name, this.codec, { BinaryMessenger? binaryMessenger })
: assert(name != null),
assert(codec != null),
_binaryMessenger = binaryMessenger;
-
name
類似于MethodChannel,標記名稱與原生的對應 -
codec
編解碼器,這里使用StandardMessageCodec()。
注意:關于編解碼器原理
會在分析渲染引擎
講解
2.發送數據
/// Sends the specified [message] to the platform plugins on this channel.
///
/// Returns a [Future] which completes to the received response, which may
/// be null.
Future<T?> send(T message) async {
return codec.decodeMessage(await binaryMessenger.send(name, codec.encodeMessage(message)));
}
-
message
,發送一個任意類型的數據。(注意這里不能發送Flutter對象/原生對象)
3.接收數據
void setMessageHandler(Future<T> Function(T? message)? handler) {
if (handler == null) {
binaryMessenger.setMessageHandler(name, null);
} else {
binaryMessenger.setMessageHandler(name, (ByteData? message) async {
return codec.encodeMessage(await handler(codec.decodeMessage(message)));
});
}
}
-
message
, dynamic,接收一個動態類型數據。與發送數據時傳入有關 - 必須返回一個Future
2.使用basicChannel調起系統相冊
- Flutter代碼
final BasicMessageChannel _basicMessageChannel = BasicMessageChannel('pickerImage_channel', StandardMessageCodec());
File? _avatarFile;
@override
void initState() {
// TODO: implement initState
super.initState();
_basicMessageChannel.setMessageHandler((message) {
String imagePath = (message as String).substring(7);
print(imagePath);
setState(() {
_avatarFile = File(imagePath);
});
return Future((){});
});
}
@override
Widget build(BuildContext context) {
...省略中間步驟。詳細代碼見MethodChannel
_basicMessageChannel.send('picker_Image');
...省略中間步驟
}
- iOS代碼
@interface AppDelegate()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (nonatomic, strong) FlutterMethodChannel *channel;
@property (nonatomic, strong) FlutterBasicMessageChannel *basicMessageChannel;
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[GeneratedPluginRegistrant registerWithRegistry:self];
// Override point for customization after application launch.
FlutterViewController *flutterVc = (FlutterViewController *)self.window.rootViewController;
// self.channel = [FlutterMethodChannel methodChannelWithName:@"picker_images" binaryMessenger:flutterVc.binaryMessenger];
self.basicMessageChannel = [FlutterBasicMessageChannel messageChannelWithName:@"pickerImage_channel" binaryMessenger:flutterVc.binaryMessenger];
UIImagePickerController *pickerVc = [[UIImagePickerController alloc] init];
pickerVc.delegate = self;
// [self.channel setMethodCallHandler:^(FlutterMethodCall * _Nonnull call, FlutterResult _Nonnull result) {
// if ([call.method isEqualToString:@"select_image"]) {
// NSLog(@"選擇圖片");
// [flutterVc presentViewController:pickerVc animated:true completion:nil];
// }
// }];
[self.basicMessageChannel setMessageHandler:^(id _Nullable message, FlutterReply _Nonnull callback) {
if ([message isEqual:@"picker_Image"]) {
NSLog(@"選擇圖片");
[flutterVc presentViewController:pickerVc animated:true completion:nil];
}
}];
return [super application:application didFinishLaunchingWithOptions:launchOptions];
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info {
NSLog(@"%@", info);
[picker dismissViewControllerAnimated:true completion:^{
NSString * imagePath = [NSString stringWithFormat:@"%@",info[@"UIImagePickerControllerImageURL"]];
// [self.channel invokeMethod:@"imagePath" arguments:imagePath];
[self.basicMessageChannel sendMessage:imagePath];
}];
}
@end
三.EventChannel
1.Dart相關Api
1.構造方法
/// Creates an [EventChannel] with the specified [name].
///
/// The [codec] used will be [StandardMethodCodec], unless otherwise
/// specified.
///
/// Neither [name] nor [codec] may be null. The default [ServicesBinding.defaultBinaryMessenger]
/// instance is used if [binaryMessenger] is null.
const EventChannel(this.name, [this.codec = const StandardMethodCodec(), BinaryMessenger? binaryMessenger])
: assert(name != null),
assert(codec != null),
_binaryMessenger = binaryMessenger;
-
name
類似于MethodChannel,標記名稱與原生的對應
2.接收廣播流
Stream<dynamic> receiveBroadcastStream([ dynamic arguments ]) {}
-
[ dynamic arguments ]
,可以傳參數 -
Stream<dynamic>
,返回一個流數據<>
3.獲取流數據
StreamSubscription<T> listen(void onData(T event)?,
{Function? onError, void onDone()?, bool? cancelOnError});
-
onData(T event)
,event
傳輸的數據 -
onError
,錯誤時執行 -
onDone
,完成時執行 -
cancelOnError
,當發送錯誤時取消訂閱流 -
StreamSubscription
,訂閱對象
4.執行dispose(銷毀前)StreamSubscription
取消訂閱
Future<void> cancel();
-
Future<void>
返回值為空的Future,不作處理
3.Flutter相關代碼
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
var value = 0;
//1.構造方法
final EventChannel _eventChannel = const EventChannel('test_eventChannel');
StreamSubscription? _streamSubscription;
@override
void initState() {
// TODO: implement initState
super.initState();
/*
* 2.獲取流數據
* receiveBroadcastStream后可以跟上參數
* 例如iOS上的onListenWithArguments:eventSink:會接收到該參數
* - (FlutterError* _Nullable)onListenWithArguments:(id _Nullable)arguments
* eventSink:(FlutterEventSink)events
* */
_streamSubscription = _eventChannel.receiveBroadcastStream(111).listen((event) {
setState(() {
value = event;
});
}, onError: print, cancelOnError: true);
}
@override
void dispose() {
// TODO: implement dispose
super.dispose();
//4.執行dispose(銷毀前)取消訂閱
_streamSubscription?.cancel();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('EventChannel Demo'),),
body: Center(
child: Text('$value'),
),
),
);
}
}
3.iOS相關Api
1.構造方法
+ (instancetype)eventChannelWithName:(NSString*)name
binaryMessenger:(NSObject<FlutterBinaryMessenger>*)messenger;
-
name
,與Flutter對應 -
messenger
,二進制消息處理者
2.設置代理
- (void)setStreamHandler:(NSObject<FlutterStreamHandler>* _Nullable)handler;
@protocol FlutterStreamHandler
//設置事件流并開始發送事件
//arguments flutter給native的參數
- (FlutterError* _Nullable)onListenWithArguments:(id _Nullable)arguments
eventSink:(FlutterEventSink)events;
//取消事件流會調用
//arguments flutter給native的參數
- (FlutterError* _Nullable)onCancelWithArguments:(id _Nullable)arguments;
@end
-
FlutterStreamHandler
協議
3.保存FlutterEventSink
//保存該方法返回的FlutterEventSink
- (FlutterError* _Nullable)onListenWithArguments:(id _Nullable)arguments
eventSink:(FlutterEventSink)events;
4.發送數據
typedef void (^FlutterEventSink)(id _Nullable event);
- 使用保存好的
FlutterEventSink
發送數據
4.iOS相關代碼
import UIKit
import Flutter
@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate, FlutterStreamHandler {
var eventChannle: FlutterEventChannel!
var eventSink: FlutterEventSink?
var count = 0
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
GeneratedPluginRegistrant.register(with: self)
let flutterVc = window.rootViewController as! FlutterViewController
//1.構造方法
eventChannle = FlutterEventChannel(name: "test_eventChannel", binaryMessenger: flutterVc.binaryMessenger)
//2.設置協議
eventChannle.setStreamHandler(self)
Timer.scheduledTimer(timeInterval: 1.5, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true)
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
@objc func timerAction() {
count += 1
//4.發送數據
eventSink?(count);
}
func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? {
//3.保存FlutterEventSink
eventSink = events
return nil
}
func onCancel(withArguments arguments: Any?) -> FlutterError? {
return nil
}
}
eventChannel_demo.gif
三.原生項目調用Flutter模塊
- 必須使用
Module
-
flutter create -t module flutter_module
終端創建Module - 創建iOS項目
- 通過pod引入Flutter模塊到iOS項目中(原生項目和Module項目在同一級目錄下)
# Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'
flutter_application_path = '../flutter_module/'
load File.join(flutter_application_path, '.ios', 'Flutter', 'podhelper.rb')
target 'NativeProject' do
# Comment the next line if you don't want to use dynamic frameworks
use_frameworks!
install_all_flutter_pods(flutter_application_path)
# Pods for NativeProject
end
-
注意哦:修改Flutter代碼后,Xcode必須執行build重新構建Flutter.framework
1. Flutter相關代碼
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() => runApp(const MyApp());
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
final BasicMessageChannel _basicMessageChannel = const BasicMessageChannel('dismissChannel', StandardMessageCodec());
@override
void initState() {
// TODO: implement initState
super.initState();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('Flutter Module'),),
body: Container(
alignment: Alignment.center,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
child: const Text('返回'),
onPressed: () {
_basicMessageChannel.send('dismiss');
},
)
],
),
)
),
);
}
}
2. iOS相關代碼
import UIKit
import Flutter
class ViewController: UIViewController {
//這里使用BasicMessageChannel與Flutter交互
var messageChannel: FlutterBasicMessageChannel!
lazy var engine: FlutterEngine? = {
//這里以一個名稱創建渲染引擎
let engine = FlutterEngine(name: "test")
if engine.run() {
return engine
}
return nil
}()
var flutterVc: FlutterViewController!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
//如果這里engine為空,大概率是因為代碼問題沒有run起來。因此這里強制取包engine
flutterVc = FlutterViewController(engine: engine!, nibName: nil, bundle: nil)
flutterVc.modalPresentationStyle = .fullScreen
messageChannel = FlutterBasicMessageChannel(name: "dismissChannel", binaryMessenger: flutterVc.binaryMessenger)
messageChannel.setMessageHandler { [weak self] value, reply in
print(value ?? "") //dismiss
self?.flutterVc.dismiss(animated: true, completion: nil)
}
}
@IBAction func presentFlutterAction(_ sender: Any) {
present(flutterVc, animated: true, completion: nil)
}
}
flutter_module.gif