Flutter嵌入原有的iOS App 中

1.创建Flutter Module

从 Flutter Module 说起,首先在iOS 项目同级文件下创建一个Flutter Module(一个flutter的项目吧)

flutter create --template module flutter_test_module

Flutter App 和 Flutter Module 的不同之处在于 pubspec.yaml 的最后一段:

# This section identifies your Flutter project as a module meant for
# embedding in a native host app.  These identifiers should _not_ ordinarily
# be changed after generation - they are used to ensure that the tooling can
# maintain consistency when adding or modifying assets and plugins.
# They also do not have any bearing on your native host application's
# identifiers, which may be completely independent or the same as these.
module:
androidX: true
androidPackage: com.example.flutter_test_module
iosBundleIdentifier: com.example.flutterTestModule

这一段代码,把该 Flutter 项目标注为一个 module,用于嵌入到原生 app 里。

这里面设置了是否使用 androidx,Android 和 iOS 的 APP id

2.iOS嵌入Flutter 需要的frameworks:

  • 1.Flutter.framework
  • 2.App.framework
  • 3.FlutterPluginRegistrant.framework (如果有用到原生的插件 - 非纯 dart 编写)
  • 4.Pods_Runner.framework(如果有用到原生的插件 - 非纯 dart 编写)
  • 5.*.framework(插件的 framework)


    image.png

3.创建完后 给ios 打包

flutter build ios --release --no-codesign

打包出来的路径为:
build->ios->Release-iphoneos

4.使用 cocoapods + git 来管理

使用命令创建一个名为 flutter-lib的私有库。:

pod lib create flutter-lib

打开 flutter-lib.podspec

91600678484_.pic.jpg

end 前加入一行代码:

s.ios.vendored_frameworks = 'ios_frameworks/App.framework','ios_frameworks/Flutter.framework','ios_frameworks/FlutterPluginRegistrant.framework','ios_frameworks/shared_preferences.framework'

在在文件夹内创建一个名为 ios_frameworks 的文件夹,把刚次啊的frameworks 全部粘贴过来。
(见第2点)
这个时候我们原生项目就可以引入这个库啦:

platform :ios, '9.0'
flutter_application_path = '../flutter_module/'
load File.join(flutter_application_path, '.ios', 'Flutter', 'podhelper.rb')

target 'Flutter_Add_iOS' do
pod 'Masonry','~> 0.6'

inhibit_all_warnings!
install_all_flutter_pods(flutter_application_path)

pod 'flutter-lib', :path => '../flutter_module/flutter-lib'
end

当然,我们不可能都用本地路径来引入,所以我们把这整个 flutter-lib文件夹传到 git 上,修改podfile中的地址,pod install就行啦。

5 在iOS项目中怎么去运行flutter 项目

5.1 先定义一个FlutterEngine

import UIKit
import Flutter
import FlutterPluginRegistrant
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

   lazy var flutterEngine = FlutterEngine(name: "my flutter engine")

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

5.2 在在需要push 的地方

let flutterEngine = (UIApplication.shared.delegate as! AppDelegate).flutterEngine
let flutterVC = FlutterViewController(engine: flutterEngine, nibName: nil, bundle: nil)
self?.present(flutterVC, animated: true, completion: nil)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。