Flutter -- 16.混合开发

混合开发一般分2种

  • Flutter调用原生项目代码(MethodChannelBasicMessageChannelEventChannel
    • MethodChannel实现Flutter与原生双向发送消息
    • BasicMessageChannel 实现Flutter与原生双向发送数据
    • EventChannel 实现原生向Flutter发送消息
    • 当多个相同name的Channel绑定时,只有最后那个能收到消息。(只能1对1,与底层有关系,c++源码为一个字典存储,字典的name为Channel的name,value为执行的闭包(这里的hander),因此最后由name查到一个闭包执行,谁最后添加谁就是那个闭包)
  • 原生项目使用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
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 202,905评论 5 476
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,140评论 2 379
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 149,791评论 0 335
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,483评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,476评论 5 364
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,516评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,905评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,560评论 0 256
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,778评论 1 296
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,557评论 2 319
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,635评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,338评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,925评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,898评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,142评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,818评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,347评论 2 342

推荐阅读更多精彩内容