前言
前一篇文章讲解了Android原生工程如何集成Flutter项目的具体过程,Flutter混合开发(一):Android项目集成Flutter模块详细指南 ,本篇将带着大家来一起学习原生iOS项目如何集成Flutter。
因为每个版本的集成逻辑都是有差别的,所以这里交代下本篇文章的集成版本:
Flutter (channel dev,v1.10.16)
dart (v2.7.0)
Xcode (v11.2)
cocoapds (1.8.4)
创建Flutter module
假如iOS项目的路径是这样的:flutter/flutter_hybrid/iOS Project,那么我们需要在iOS Project上一层目录flutter_hybrid中创建Flutter module。
cd flutter/flutter_hybrid/
flutter create -t module flutter_module
输入后控制台打印如下:
$ flutter create -t module flutter_module
Creating project flutter_module...
flutter_module/test/widget_test.dart (created)
flutter_module/flutter_module.iml (created)
flutter_module/.gitignore (created)
flutter_module/.metadata (created)
flutter_module/pubspec.yaml (created)
flutter_module/README.md (created)
flutter_module/lib/main.dart (created)
flutter_module/flutter_module_android.iml (created)
flutter_module/.idea/libraries/Flutter_for_Android.xml (created)
flutter_module/.idea/libraries/Dart_SDK.xml (created)
flutter_module/.idea/modules.xml (created)
flutter_module/.idea/workspace.xml (created)
Running "flutter pub get" in flutter_module... 1.2s
Wrote 12 files.
All done!
Your module code is in flutter_module/lib/main.dart.
看到All done就表示我们项目创建好了。整个module目录和原生Flutter基本一样,主要就是Android、iOS的宿主工程和lib目录以及pubspec.yaml文件。
添加Flutter module依赖
为iOS项目添加依赖需要使用CocoaPods,如果你还没有用到CocoaPods,可以参考https://cocoapods.org/上面的说明来安装CocoaPods。
如果你的项目之前没有使用过cocoapods,那么需要进行初始化生成podfile文件,进入iOS项目的根目录执行:
pod init
然后打开podfile文件,进行配置:
# 配置
flutter_application_path = '../flutter_module/'
load File.join(flutter_application_path, '.ios', 'Flutter', 'podhelper.rb')
target 'iOSFlutterHybrid' do
# Comment the next line if you don't want to use dynamic frameworks
use_frameworks!
# Pods for iOSFlutterHybrid
# 配置
install_all_flutter_pods(flutter_application_path)
target 'iOSFlutterHybridTests' do
inherit! :search_paths
# Pods for testing
end
target 'iOSFlutterHybridUITests' do
# Pods for testing
end
配置添加好后在项目根目录运行以下命令进行安装:
pod install
控制台输出:
Analyzing dependencies
Downloading dependencies
Installing Flutter (1.0.0)
Installing FlutterPluginRegistrant (0.0.1)
Installing flutter_module (0.0.1)
Generating Pods project
Integrating client project
[!] Please close any current Xcode sessions and use `iOSFlutterHybrid.xcworkspace` for this project from now on.
Pod installation complete! There are 3 dependencies from the Podfile and 3 total pods installed.
[!] Automatically assigning platform `iOS` with version `13.2` on target `iOSFlutterHybrid` because no platform was specified. Please specify a platform for this target in your Podfile. See `https://guides.cocoapods.org/syntax/podfile.html#platform`.
这里我们看到有三个依赖安装完成了。并提醒我们关闭当前项目,在根目录下面使用iOSFlutterHybrid.xcworkspace来打开运行项目。这里可能很多人在执行命令的时候会发现提示0个依赖完成。这里有可能是你的Xcode版本的问题。因为Flutter要求最低版本是10.2及以上。
当在flutter_module/pubspec.yaml中添加一个Flutter插件时,需要在flutter_mod