Flutter 与Object-C混编开发_ios

1.iOS原有项目集成flutter

官方文档:flutter官方开发文档地址

1.第一步:首先我们要在同级工程目录podfile下创建flutter工程。

终端命令:

flutter create --template module my_flutter

文件名就是my_flutter
当然也可以通过vscode 或者 android studio来创建此工程在指定位置下。
因为是完整的空flutter项目 所以也可以独立运行

2.第二步:配置podfile文件

在原有iOS项目里想要调用flutter,其实就是一个本地模块。类似与我们pod引用本地模块一样的方式。

podfile配置如下:

在target '' do 配置上面加上

## ==============Flutter ==============_
  flutter_application_path = 'flutter_moudle'
  load File.join(flutter_application_path, '.ios', 'Flutter', 'podhelper.rb')
  install_all_flutter_pods(flutter_application_path)

  ## ==============Flutter ==============_

flutter_application_path 指向你的flutter工程名称,我这里的工程名称是flutter_moudle为例。

load File.join(flutter_application_path, '.ios', 'Flutter', 'podhelper.rb')
的含义是指向flutter_moudle工程目录下的 .ios/Flutter/podhelper.rb

如果你的工程没有.ios文件,那你需要用flutter build ios 命令来初始化flutter iOS工程。

之后执行 pod install --verbose

运行成功会在iOS工程的pod目录下有如图目录:

Flutter 与Object-C混编开发_ios_02

3.第三步:xcode 配置flutter

在xcode的general 里配置flutter.xcframework

Flutter 与Object-C混编开发_#import_03

4.AppDelegate配置

  • AppDelegate.h里添加引用
#import <Flutter/Flutter.h>
#import <FlutterPluginRegistrant/GeneratedPluginRegistrant.h>

并在interface里声明flutter引擎对象

@property (nonatomic,strong)FlutterEngine *flutterEngine;

  • AppDelegate.m 里找到didFinishLaunchingWithOptions方法。在应用启动完成时添加引擎初始化。
self.flutterEngine = [[FlutterEngine alloc] initWithName:@"my flutter engine"];
// Runs the default Dart entrypoint with a default Flutter route.
[self.flutterEngine run];
// Used to connect plugins (only if you have plugins with iOS platform code).
[GeneratedPluginRegistrant registerWithRegistry:self.flutterEngine];
return YES;

这里基本就是配置完成了

5.调用flutter引擎 跳转到fluter页面

在你想调用的地方添加

FlutterEngine *flutterEngine =
            ((AppDelegate *)UIApplication.sharedApplication.delegate).flutterEngine;
            
FlutterViewController *flutterViewController =
            [[FlutterViewController alloc] initWithEngine:flutterEngine nibName:nil bundle:nil];
            
[self.viewController.navigationController pushViewController:flutterViewController animated:NO];

直接运行工程就可以看到效果了。


2.常见集成问题

  • 1.编译报错:target 9.0问题和undefined method `flutter_additional_ios_build_settings'

解决方案:
podfile里将flutter_additional_ios_build_settings注释掉即可

post_install do |installer|
 installer.pods_project.targets.each do |target|
     target.build_configurations.each do |config|
         config.build_settings['IPHONEOS_DEPLOYMENT_T>ARGET'] = '9.0'
     end
#    flutter_additional_ios_build_settings(target)
 end
end

  • 2.Xcode Command PhaseScriptExecution failed with a nonzero exit code

解决方案:

清缓存

在Xcode菜单栏选择File -> Workspace Setting -> Build System new Build System(Default) 重新运行即可。