混合开发一般分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,)
],
),
)
],
),
))
],
),
),
),
);
}
}
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
}
}
三.原生项目调用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)
}
}