Flutter项目:Android Studio(Win10)配置iOS Firebase plist与多Flavor环境
问题1:在Windows 10的Android Studio中,给Flutter项目添加Firebase的GoogleService-Info.plist文件
GoogleService-Info.plist是iOS平台的Firebase配置文件,虽然你用的是Windows上的Android Studio,还是可以通过以下步骤完成配置:
- 获取配置文件:先登录Firebase控制台,找到你的iOS应用(如果还没创建,先按流程注册,注意包名要和Flutter项目的iOS包名一致),下载对应的
GoogleService-Info.plist文件。 - 放入指定目录:在Android Studio中切换到「Project」视图,找到项目根目录下的
ios/Runner文件夹,将下载好的plist文件复制到这里。 - 确保文件被iOS项目引用:因为Windows上没有Xcode,需要手动编辑Xcode项目文件:
- 打开
ios/Runner.xcodeproj/project.pbxproj文件 - 找到
/* Begin PBXFileReference section */,添加一行(注意替换ID为文件中未使用的唯一数字):12345678 /* GoogleService-Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = GoogleService-Info.plist; sourceTree = "<group>"; }; - 接着找到
Runner分组的children列表(在/* Begin PBXGroup section */下),把上面的ID加入进去:children = ( ... 12345678 /* GoogleService-Info.plist */, ... ); - 最后在
/* Begin PBXResourcesBuildPhase section */的files列表中,添加对应的构建文件条目:
并在files = ( ... 87654321 /* GoogleService-Info.plist in Resources */, ... );/* Begin PBXBuildFile section */中添加:87654321 /* GoogleService-Info.plist in Resources */ = {isa = PBXBuildFile; fileRef = 12345678 /* GoogleService-Info.plist */; };
- 打开
- 可选(若有Mac环境):如果之后能用到Mac,直接打开
ios/Runner.xcodeproj,把plist文件拖到Runner文件夹下,勾选「Copy items if needed」并确保关联到Runner目标,这样更简单。
问题2:为iOS的dev/prod环境配置不同的GoogleService-Info.plist文件
你已经在src/dev和src/prod下放了对应的配置文件,接下来可以通过两种方式完成多环境配置:
方式一:使用Xcode多Target(原生iOS方式)
这种方式更符合iOS的原生多环境规范:
- 创建iOS环境目录:在项目的
ios文件夹下新建RunnerDev和RunnerProd两个子文件夹,分别把src/dev和src/prod下的GoogleService-Info.plist复制进去。 - 编辑Xcode项目文件:
- 打开
ios/Runner.xcodeproj/project.pbxproj,找到/* Begin PBXNativeTarget section */下的Runner目标块,复制一份并修改:- 替换唯一ID
- 把
name改成RunnerDev - 更新
PRODUCT_NAME和PRODUCT_BUNDLE_IDENTIFIER(要和Firebase dev项目的包名一致) - 重复此操作创建
RunnerProd目标
- 分别为两个新目标添加对应的plist文件引用(参考问题1的步骤),确保每个Target的Resources构建阶段只包含对应环境的plist。
- 打开
- 配置Flutter侧的Flavor:
在pubspec.yaml中添加Flavor配置:
创建对应的入口文件flutter: flavors: dev: name: 我的应用-开发版 bundleId: com.example.myapp.dev prod: name: 我的应用 bundleId: com.example.myapplib/main_dev.dart和lib/main_prod.dart,分别初始化Firebase。 - 运行指定环境:
flutter run --flavor dev -t lib/main_dev.dart flutter run --flavor prod -t lib/main_prod.dart
方式二:使用构建脚本(跨平台更简便)
这种方式无需修改Xcode Target,通过脚本复制对应环境的plist文件:
- 编写PowerShell脚本:在项目根目录创建
copy_ios_plist.ps1,内容如下:param( [string]$flavor ) $source = "src/$flavor/GoogleService-Info.plist" $dest = "ios/Runner/GoogleService-Info.plist" Copy-Item -Path $source -Destination $dest -Force Write-Host "已将$flavor环境的plist文件复制到iOS目录" - 构建前执行脚本:
- 构建开发版前先运行:
然后执行:.\copy_ios_plist.ps1 -flavor devflutter build ios --flavor dev -t lib/main_dev.dart - 生产版同理,替换
dev为prod即可。
- 构建开发版前先运行:
- 集成到Android Studio:在Android Studio的「Run/Debug Configurations」中,为每个Flavor添加「Before launch」任务,选择「Run External Tool」,配置运行上述PowerShell脚本,这样每次运行对应Flavor时会自动复制正确的plist。
内容的提问来源于stack exchange,提问作者Vishal Vishvakarma
相关产品推荐
相关产品推荐

