作者:晨曦_iOS

虽然一般不建议在原生项目中嵌入Flutter,但是Flutter也可以支持这种方式,下面我们来看一下具体的实现。

原生嵌入 Flutter 的工程配置



flutter UI风格 ios flutter module ios_python

如图,我们想使原生嵌入Flutter的话,使用Android Studio创建项目的时候就要选择Module进行创建,使之作为一个模块来开发。



flutter UI风格 ios flutter module ios_flutter UI风格 ios_02

打开我们新建的flutter_module工程目录可以看到,与创建的Flutter App相比,文件里面仍然有AndroidiOS工程文件,但是这里只是为了让我们做调试用的,而且这两个文件都是隐藏文件,不过AndroidiOS工程中不建议加入原生代码,而且即使加了,打包的时候也不会被打包进去。flutter_module是一个纯Flutter的工程。



flutter UI风格 ios flutter module ios_android_03

  • Podfile文件配置
flutter_application_path = '../flutter_module'
load File.join(flutter_application_path,'.iOS','Flutter','podhelper.rb')

platform :ios, '9.0'

target 'NativeDemo' do
  install_all_flutter_pods(flutter_application_path)
  use_frameworks!

  # Pods for NativeDemo

end

我们使用Xcode创建一个原生工程,NativeDemo,使用终端,cdNativeDemo目录下,pod init,然后配置Podfile文件,然后执行pod install

pod install完成之后,打开原生项目,引用头文件#import <Flutter/Flutter.h>,可以成功的话就代表配置成功,现在的话原生工程与Flutter就有联系了,下面我们就可以实现代码了,来使原生工程中嵌入Flutter

原生项目调起 Flutter 页面

  • 原生代码部分
#import "ViewController.h"
#import <Flutter/Flutter.h>

@interface ViewController ()
@property(nonatomic, strong) FlutterEngine* flutterEngine;
@property(nonatomic, strong) FlutterViewController* flutterVc;
@property(nonatomic, strong) FlutterBasicMessageChannel * msgChannel;
@end

@implementation ViewController

-(FlutterEngine *)flutterEngine
{
    if (!_flutterEngine) {
        FlutterEngine * engine = [[FlutterEngine alloc] initWithName:@"hank"];
        if (engine.run) {
            _flutterEngine = engine;
        }
    }
    return _flutterEngine;
}

- (IBAction)pushFlutter:(id)sender {
    
    self.flutterVc.modalPresentationStyle = UIModalPresentationFullScreen;

    //创建channel
    FlutterMethodChannel * methodChannel = [FlutterMethodChannel methodChannelWithName:@"one_page" binaryMessenger:self.flutterVc.binaryMessenger];
    //告诉Flutter对应的页面
    [methodChannel invokeMethod:@"one" arguments:nil];
    
    //弹出页面
    [self presentViewController:self.flutterVc animated:YES completion:nil];
    
    //监听退出
    [methodChannel setMethodCallHandler:^(FlutterMethodCall * _Nonnull call, FlutterResult  _Nonnull result) {
        //如果是exit我就退出页面!
        if ([call.method isEqualToString:@"exit"]) {
            [self.flutterVc dismissViewControllerAnimated:YES completion:nil];
        }
    }];
}
- (IBAction)pushFlutterTwo:(id)sender {
    self.flutterVc.modalPresentationStyle = UIModalPresentationFullScreen;

    //创建channel
    FlutterMethodChannel * methodChannel = [FlutterMethodChannel methodChannelWithName:@"two_page" binaryMessenger:self.flutterVc.binaryMessenger];
    //告诉Flutter对应的页面
    [methodChannel invokeMethod:@"two" arguments:nil];
    
    //弹出页面
    [self presentViewController:self.flutterVc animated:YES completion:nil];
    
    //监听退出
    [methodChannel setMethodCallHandler:^(FlutterMethodCall * _Nonnull call, FlutterResult  _Nonnull result) {
        //如果是exit我就退出页面!
        if ([call.method isEqualToString:@"exit"]) {
            [self.flutterVc dismissViewControllerAnimated:YES completion:nil];
        }
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.flutterVc = [[FlutterViewController alloc] initWithEngine:self.flutterEngine nibName:nil bundle:nil];
    self.msgChannel = [FlutterBasicMessageChannel messageChannelWithName:@"messageChannel" binaryMessenger:self.flutterVc.binaryMessenger];
    
    [self.msgChannel setMessageHandler:^(id  _Nullable message, FlutterReply  _Nonnull callback) {
        NSLog(@"收到Flutter的:%@",message);
    }];
    
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    static int a = 0;
    [self.msgChannel sendMessage:[NSString stringWithFormat:@"%d",a++]];
}

在原生代码部分我们定义了三个属性,flutterEngine代表引擎对象,flutterVcFlutterViewController类型的控制器对象,msgChannel是通信方式中的一种channel,为FlutterBasicMessageChannel类型,下面会有介绍。

在这里我们实现了pushFlutterpushFlutterTwo两个方法,代表调起两个不同的Flutter页面。在这两个方法中,我们首先创建methodChannel对象,并分别传入onetwo两个字符串标识,并且binaryMessenger传参传入的都是self.flutterVc.binaryMessenger。在两个方法中分别调用invokeMethod方法,向Flutter页面发送消息,然后弹出页面,并且实现setMethodCallHandler方法,在闭包中判断call.method isEqualToString:@"exit",进行页面的退出。

  • Flutter 代码部分
// ignore_for_file: avoid_print

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 MethodChannel _oneChannel = const MethodChannel('one_page');
  final MethodChannel _twoChannel = const MethodChannel('two_page');
  final BasicMessageChannel _messageChannel =
      const BasicMessageChannel('messageChannel', StandardMessageCodec());

  String pageIndex = 'one';

  @override
  void initState() {
    super.initState();

    _messageChannel.setMessageHandler((message) {
      print('收到来自iOS的$message');
      return Future(() {});
    });

    _oneChannel.setMethodCallHandler((call) {
      pageIndex = call.method;
      print(call.method);
      setState(() {});
      return Future(() {});
    });
    _twoChannel.setMethodCallHandler((call) {
      pageIndex = call.method;
      print(call.method);
      setState(() {});
      return Future(() {});
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: _rootPage(pageIndex),
    );
  }

  //根据pageIndex来返回页面!
  Widget _rootPage(String pageIndex) {
    switch (pageIndex) {
      case 'one':
        return Scaffold(
          appBar: AppBar(
            title: Text(pageIndex),
          ),
          body: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              ElevatedButton(
                onPressed: () {
                  _oneChannel.invokeMapMethod('exit');
                },
                child: Text(pageIndex),
              ),
              TextField(
                onChanged: (String str) {
                  _messageChannel.send(str);
                },
              )
            ],
          ),
        );
      case 'two':
        return Scaffold(
          appBar: AppBar(
            title: Text(pageIndex),
          ),
          body: Center(
            child: ElevatedButton(
              onPressed: () {
                _twoChannel.invokeMapMethod('exit');
              },
              child: Text(pageIndex),
            ),
          ),
        );
      default:
        return Scaffold(
          appBar: AppBar(
            title: Text(pageIndex),
          ),
          body: Center(
            child: ElevatedButton(
              onPressed: () {
                const MethodChannel('default_page').invokeMapMethod('exit');
              },
              child: Text(pageIndex),
            ),
          ),
        );
    }
  }
}

Flutter代码中我们定义了_oneChannel_twoChannel这两个变量用了接收原生页面发送的消息,并且向原生页面发送消息。定义了变量pageIndex用来标识创建那个页面。

initState方法中调用setMethodCallHandler方法,获取到原生页面传来的数据并赋值给pageIndex,然后调用setState方法。

build方法中我们调用_rootPage方法来判断创建哪个页面。并且分别在这两个页面的点击事件中调用invokeMapMethod方法,代表退出页面,原生页面在setMethodCallHandler闭包中接收到exit数据后就会调用[self.flutterVc dismissViewControllerAnimated:YES completion:nil],进行页面的退出。

Flutter 与原生的通信

  • MethodChannelFlutterNative端相互调用,调用后可以返回结果,可以Native端主动调用,也可以Flutter主动调用,属于双向通信。此方式为最常用的方式,Native端调用需要在主线程中执行。
  • BasicMessageChannel: 用于使用指定的编解码器对消息进行编码和解码,属于双向通信,可以Native端主动调用,也可Flutter主动调用。
  • EventChannel:用于数据流(event streams)的通信,Native端主动发送数据给Flutter,通常用于状态的监听,比如网络变化、传感器数据等。

Flutter与原生通信有三种方式,Flutter为我们提供了三种Channel,分别是MethodChannelBasicMessageChannelEventChannel。但是我们比较常用的就是MethodChannelBasicMessageChannel这两种。因为MethodChannel前面已经讲过了,所以这里我们介绍一下BasicMessageChannel的用法。

BasicMessageChannel 用法

BasicMessageChannel的用法与FlutterMethodChannel类似,在上面的代码示例中,首先在Flutter代码中我们也是定义一个BasicMessageChannel类型的变量_messageChannel,在_messageChannelsetMessageHandler闭包中接收来自于原生页面发来的消息,调用_messageChannelsend方法向原生页面进行通信,在输入框文字变化的时候都会调用send方法。在原生代码中也是类似,定义了msgChannel属性,setMessageHandler中的block负责接收消息,sendMessage发送消息,在touchesBegan中向Flutter传递a的累加值。

作者:晨曦_iOS