混合開發(fā)一般分2種
-
Flutter調(diào)用原生項(xiàng)目代碼(
MethodChannel
电湘、BasicMessageChannel
仅醇、EventChannel
)- MethodChannel
實(shí)現(xiàn)Flutter與原生雙向發(fā)送消息
- BasicMessageChannel
實(shí)現(xiàn)Flutter與原生雙向發(fā)送數(shù)據(jù)
- EventChannel
實(shí)現(xiàn)原生向Flutter發(fā)送消息
- 當(dāng)多個(gè)相同name的Channel綁定時(shí),只有最后那個(gè)能收到消息刽锤。(只能1對(duì)1是尔,與底層有關(guān)系烙样,
c++源碼為一個(gè)字典存儲(chǔ)贴汪,字典的name為Channel的name,value為執(zhí)行的閉包(這里的hander)休吠,因此最后由name查到一個(gè)閉包執(zhí)行扳埂,誰最后添加誰就是那個(gè)閉包
)
- MethodChannel
-
原生項(xiàng)目使用Flutter項(xiàng)目功能(
Module
),這里只介紹iOS相關(guān)邏輯
一.MethodChannel
1.相關(guān)Api
1.構(gòu)造方法
/// 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
當(dāng)前MethodChannel的名稱瘤礁,與原生的對(duì)應(yīng)
2.發(fā)送數(shù)據(jù)
Future<T?> invokeMethod<T>(String method, [ dynamic arguments ]) {
return _invokeMethod<T>(method, missingOk: false, arguments: arguments);
}
-
invokeMethod
發(fā)送消息 -
method
消息名 -
dynamic
參數(shù)
3.接收數(shù)據(jù)
void setMethodCallHandler(Future<dynamic> Function(MethodCall call)? handler) {
binaryMessenger.setMessageHandler(
name,
handler == null
? null
: (ByteData? message) => _handleAsMethodCall(message, handler),
);
}
- 當(dāng)執(zhí)行了
invoke
的回調(diào) - 必須返回一個(gè)Future
-
MethodCall
回調(diào)數(shù)據(jù)阳懂,包括method、arguments等信息
2.使用MethodChannel調(diào)起系統(tǒng)相冊(cè)
- 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
對(duì)應(yīng)MethodChannel(Flutter) -
FlutterViewController
對(duì)應(yīng)的Flutter渲染引擎控制器(在原生上只有一個(gè)控制器)
- Flutter端代碼(只貼出關(guān)鍵代碼)
class _MineHeaderState extends State<MineHeader> {
final MethodChannel _methodChannel = MethodChannel('picker_images');
File? _avatarFile;
@override
void initState() {
// TODO: implement initState
super.initState();
//選擇圖片后的回調(diào)
_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: () {
//發(fā)送消息給原生
_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的個(gè)性簽名', style: TextStyle(fontSize: 14)),
Image.asset('images/icon_right.png', width: 15,)
],
),
)
],
),
))
],
),
),
),
);
}
}
methodChannel_ImagePicker.gif
2.使用image_picker調(diào)用系統(tǒng)相冊(cè)
- image_picker官方的選擇圖片插件
- 不用單獨(dú)去實(shí)現(xiàn)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;
});
});
}
- 當(dāng)然這里也可以使用異步任務(wù)柜思,但是
必須要使用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.相關(guān)Api
1.構(gòu)造方法
/// 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岩调,標(biāo)記名稱與原生的對(duì)應(yīng) -
codec
編解碼器,這里使用StandardMessageCodec()赡盘。
注意:關(guān)于編解碼器原理
會(huì)在分析渲染引擎
講解
2.發(fā)送數(shù)據(jù)
/// 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
号枕,發(fā)送一個(gè)任意類型的數(shù)據(jù)。(注意這里不能發(fā)送Flutter對(duì)象/原生對(duì)象)
3.接收數(shù)據(jù)
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亡脑,接收一個(gè)動(dòng)態(tài)類型數(shù)據(jù)堕澄。與發(fā)送數(shù)據(jù)時(shí)傳入有關(guān) - 必須返回一個(gè)Future
2.使用basicChannel調(diào)起系統(tǒng)相冊(cè)
- 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) {
...省略中間步驟。詳細(xì)代碼見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相關(guān)Api
1.構(gòu)造方法
/// 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霉咨,標(biāo)記名稱與原生的對(duì)應(yīng)
2.接收廣播流
Stream<dynamic> receiveBroadcastStream([ dynamic arguments ]) {}
-
[ dynamic arguments ]
蛙紫,可以傳參數(shù) -
Stream<dynamic>
,返回一個(gè)流數(shù)據(jù)<>
3.獲取流數(shù)據(jù)
StreamSubscription<T> listen(void onData(T event)?,
{Function? onError, void onDone()?, bool? cancelOnError});
-
onData(T event)
途戒,event
傳輸?shù)臄?shù)據(jù) -
onError
坑傅,錯(cuò)誤時(shí)執(zhí)行 -
onDone
,完成時(shí)執(zhí)行 -
cancelOnError
喷斋,當(dāng)發(fā)送錯(cuò)誤時(shí)取消訂閱流 -
StreamSubscription
唁毒,訂閱對(duì)象
4.執(zhí)行dispose(銷毀前)StreamSubscription
取消訂閱
Future<void> cancel();
-
Future<void>
返回值為空的Future,不作處理
3.Flutter相關(guān)代碼
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.構(gòu)造方法
final EventChannel _eventChannel = const EventChannel('test_eventChannel');
StreamSubscription? _streamSubscription;
@override
void initState() {
// TODO: implement initState
super.initState();
/*
* 2.獲取流數(shù)據(jù)
* receiveBroadcastStream后可以跟上參數(shù)
* 例如iOS上的onListenWithArguments:eventSink:會(huì)接收到該參數(shù)
* - (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.執(zhí)行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相關(guān)Api
1.構(gòu)造方法
+ (instancetype)eventChannelWithName:(NSString*)name
binaryMessenger:(NSObject<FlutterBinaryMessenger>*)messenger;
-
name
星爪,與Flutter對(duì)應(yīng) -
messenger
浆西,二進(jìn)制消息處理者
2.設(shè)置代理
- (void)setStreamHandler:(NSObject<FlutterStreamHandler>* _Nullable)handler;
@protocol FlutterStreamHandler
//設(shè)置事件流并開始發(fā)送事件
//arguments flutter給native的參數(shù)
- (FlutterError* _Nullable)onListenWithArguments:(id _Nullable)arguments
eventSink:(FlutterEventSink)events;
//取消事件流會(huì)調(diào)用
//arguments flutter給native的參數(shù)
- (FlutterError* _Nullable)onCancelWithArguments:(id _Nullable)arguments;
@end
-
FlutterStreamHandler
協(xié)議
3.保存FlutterEventSink
//保存該方法返回的FlutterEventSink
- (FlutterError* _Nullable)onListenWithArguments:(id _Nullable)arguments
eventSink:(FlutterEventSink)events;
4.發(fā)送數(shù)據(jù)
typedef void (^FlutterEventSink)(id _Nullable event);
- 使用保存好的
FlutterEventSink
發(fā)送數(shù)據(jù)
4.iOS相關(guān)代碼
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.構(gòu)造方法
eventChannle = FlutterEventChannel(name: "test_eventChannel", binaryMessenger: flutterVc.binaryMessenger)
//2.設(shè)置協(xié)議
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.發(fā)送數(shù)據(jù)
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
三.原生項(xiàng)目調(diào)用Flutter模塊
- 必須使用
Module
-
flutter create -t module flutter_module
終端創(chuàng)建Module - 創(chuàng)建iOS項(xiàng)目
- 通過pod引入Flutter模塊到iOS項(xiàng)目中(原生項(xiàng)目和Module項(xiàng)目在同一級(jí)目錄下)
# 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必須執(zhí)行build重新構(gòu)建Flutter.framework
1. Flutter相關(guān)代碼
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相關(guān)代碼
import UIKit
import Flutter
class ViewController: UIViewController {
//這里使用BasicMessageChannel與Flutter交互
var messageChannel: FlutterBasicMessageChannel!
lazy var engine: FlutterEngine? = {
//這里以一個(gè)名稱創(chuàng)建渲染引擎
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為空顽腾,大概率是因?yàn)榇a問題沒有run起來近零。因此這里強(qiáng)制取包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