iOS项目中集成 Flutter 模块 2021-06-20

环境

  • Flutter 2.3.0
  • Dart 2.14.0

准备

  • 配置好Flutter环境,具体细节 参考Flutter官网
  • 终端命令行创建Flutter Module
flutter create --template module flutter_module
  • Xcode 创建 iOS Project(FlutterDemo)
  • 创建并配置 Podfile 文件
$flutter_path = '../flutter_module/'

target 'FlutterDemo' do
    flutter_application_path = $flutter_path
    load File.join(flutter_application_path, '.ios', 'Flutter', 'podhelper.rb')
    install_all_flutter_pods(flutter_application_path)
end
  • pod install

页面跳转

AppDelegate.swift

import Flutter

lazy var flutterEngine: FlutterEngine = {
        // "main" 为对应的dart文件
        let engine: FlutterEngine = FlutterEngine(name: "main", project: nil)
        return engine
    }()

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        flutterEngine.run(withEntrypoint: nil)        
        return true
    }

Native跳转Flutter页面

let appDelegate: AppDelegate = UIApplication.shared.delegate as! AppDelegate
let vc: FlutterViewController = FlutterViewController(engine: appDelegate.flutterEngine, nibName: nil, bundle: nil)
navigationController?.pushViewController(vc, animated: true)

使用CocoaPods引入远程仓库Flutter Module

  • 上面集成是通过指定本地路径Flutter文件,才能正确引入
  • 创建Flutter的时候将目录地址带进了文件内 导致如果将Flutter Module地址移动地址,将不能正确runing 主Project
    实际开发过程中,往往将Module直接放在远程仓库上,需要的时候再通过pod install集成到主项目中, 基于以上两点,上面实现 无法满足实际需求。

解决方案:Flutter Module 生成 Framework

  1. 先打包Framework
flutter build ios-framework --output=./path
  1. 将导出的所有Framework都合并架构
/// 查看 framework 支持的架构
lipo -info Flutter.framework  
/// 合并架构
lipo -create Flutter-1.framework/Flutter Flutter-2.framework/Flutter -output Flutter.framework
  1. 创建私有库
pod lib create FlutterLib

4.修改podspec文件, 添加依赖flutter module打包生成所有framework

 s.ios.vendored_frameworks = 'ios_frameworks/App.framework',
  'ios_frameworks/Flutter.framework'
  1. 将第2步合并的所有framework移动到 第4步指定的目录中,如ios_frameworks目录下
  2. 在主app下通过引用私有库 FlutterLib 引入Flutter Module

你可能感兴趣的:(iOS项目中集成 Flutter 模块 2021-06-20)