今天,学习下,如何在iOS原生工程中集成Flutter模块

  1. ok,首先我们使用Xcode新建一个iOS原生工程,先放着.
    然后通过flutter create -t module flutter_module新建一个flutter的模块,这里名字随意.以flutter_module为例.iosAddFlutter1
  2. 然后在iOS原生工程中,使用pod导入flutter:
    首先,终端上先通过pod init为原生工程创建Podfile文件.iosAddFlutter2 然后在该Podfile文件中添加以下:
1
2
3
  flutter_application_path = '../flutter_module/'
eval(File.read(File.join(flutter_application_path, '.ios', 'Flutter', 'podhelper.rb')), binding)

注意路径正确.

  1. 终端 cd到iOS原生项目根目录下. 执行pod install

    iosAddFlutter3
  2. 通过点击XXXX.xcworkspace文件打开Xcode.
    找到”TAGGETS”->”Build Settings”->”Enable Bitcode”
    首先把项目bitcode关闭.

    iosAddFlutter5
  3. 找到”TAGGETS”->”Build Settings”->”Enable Phases”.
    点击+号,新建一个”New Run Script Phase”.
    其中加入:

1
2
3
  "$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh" build
"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh" embed

然后,把它移动Target Dependencied下面.
iosAddFlutter5 iosAddFlutter6

ok.Xcode build下,正确情况下是工程好的.集成步骤完毕.

然后我们在 ViewController.m中通过presentViewController的方式跳至flutter模块即可.
首先,引入

1
2
3
#import <Flutter/Flutter.h>
#import <FlutterPluginRegistrant/GeneratedPluginRegistrant.h>

其中,可以为flutter模块传个参数,通过
setInitialRoute.
该文件完整代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
//
// ViewController.m
// iOSAddFlutter
//
// Created by Shaoting Zhou on 2019/5/29.
// Copyright © 2019 Shaoting Zhou. All rights reserved.
//

#import "ViewController.h"


#import <Flutter/Flutter.h>
#import <FlutterPluginRegistrant/GeneratedPluginRegistrant.h>

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];
UIButton *button = [[UIButton alloc]init];
[button setTitle:@"跳至Flutter模块" forState:UIControlStateNormal];
button.backgroundColor=[UIColor redColor];
button.frame = CGRectMake(50, 50, 200, 100);
[button setTitleColor:[UIColor redColor] forState:UIControlStateHighlighted];
[button addTarget:self action:@selector(buttonPrint) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];

// Do any additional setup after loading the view.
}

- (void)buttonPrint{
FlutterViewController * flutterVC = [[FlutterViewController alloc]init];
[flutterVC setInitialRoute:@"我是Native传给FLutter模块的"];
[self presentViewController:flutterVC animated:true completion:nil];
}



@end


flutter_module模块中,通过window.defaultRouteName的方式即可获取到iOS原生传过去的值.其中需要引入 import 'dart:ui';
源码

效果图:
iOSAddFlutter_result