Flutter

Flutter 混合开发(原生 iOS 项目交互)

2020-09-03  本文已影响0人  有何不可_bd86

对于 Flutter 的业务应用,我们更希望它可以集成到已有的项目中,这篇详细的介绍下如何将 Flutter 集成到 iOS 项目工程中,对于后续的通信、交互、管理

创建 Flutter 模块

创建 iOS 工程项目,命名为 FlutterMixDemo ,当然你也可以用已有的工程来集成。

接下来我们需要创建 Flutter 模块,进入已有工程目录,这里拿我的工程目录举例:

.../FlutterDemo/  (FlutterDemo 是 iOS 工程项目)
进入在 ... 目录下,终端执行命令:
flutter create -t module flutter_module 

原生 将 Flutter 模块以 pods 的方式加入到已有项目中

cd FlutterDemo路径
pod init

这时我们项目中会多一个 Podfile 文件,我们在该文件最后面添加命令如下:

# Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'

target 'FlutterDemo' do
  # Comment the next line if you don't want to use dynamic frameworks
  use_frameworks!

  # Pods for FlutterDemo

  target 'FlutterDemoTests' do
    inherit! :search_paths
    # Pods for testing
  end

  target 'FlutterDemoUITests' do
    # Pods for testing
  end

end

# 新加命令
flutter_application_path = '../flutter_module'
eval(File.read(File.join(flutter_application_path, '.ios', 'Flutter', 'podhelper.rb')), binding)
pod install

配置 Dart 编译脚本

在项目Build Phases 选项中,点击左上角➕号按钮,选择 New Run Script Phase ,添加如下脚本

"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh" build
"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh" embed
使用 FlutterViewController

所有的 Flutter 页面公用一个Flutter实例 (FlutterViewController) 。
引入头文件
#import <Flutter/Flutter.h>
我们已点击按钮后跳入 Flutter 页面举例:

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = UIColor.whiteColor;
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button addTarget:self
               action:@selector(jumpToFlutter)
     forControlEvents:UIControlEventTouchUpInside];
    [button setTitle:@"jump to flutter" forState:UIControlStateNormal];
    [button setBackgroundColor:[UIColor orangeColor]];
    button.titleLabel.font = [UIFont systemFontOfSize:20 weight:UIFontWeightBold];
    button.frame = CGRectMake(95.0, 210.0, 160.0, 44.0);
    [self.view addSubview:button];
}

- (void)jumpToFlutter {
    FlutterViewController* flutterViewController = [[FlutterViewController alloc] init];
    [self.navigationController pushViewController:flutterViewController animated:YES];
}

不过这样跳转后本身 Flutter 页面也会有一个导航栏,原生也有一个,造成重复。当然我们可以把 Flutter 页面的 appBar 去掉就可以,如下:

 appBar: AppBar(
        title: Text('Flutter Page') ,
        leading: IconButton(icon: Icon(Icons.arrow_back_ios), onPressed:()=>Navigator.pop()),
      ),
上一篇下一篇

猜你喜欢

热点阅读