Flutter 构建错误:unable to resolve product type 'com.apple.product-type.watchkit2-extension' 的解决记录
📌 Error Log
在使用 Android Studio 或通过 flutter run
命令向 iOS 真机部署 Flutter 应用时,遇到了如下报错:
rust
Could not build the precompiled application for the device.
Error (Xcode): unable to resolve product type 'com.apple.product-type.watchkit2-extension' for platform 'iOS'
Error (Xcode): Couldn't look up product type 'com.apple.product-type.watchkit2-extension' in domain 'iphoneos': Couldn't load spec with identifier 'com.apple.product-type.watchkit2-extension' in domain 'iphoneos'
Error (Xcode): unable to resolve product type 'com.apple.product-type.application.watchapp2' for platform 'iOS'
Error (Xcode): Couldn't look up product type 'com.apple.product-type.application.watchapp2' in domain 'iphoneos': Couldn't load spec with identifier 'com.apple.product-type.application.watchapp2' in domain 'iphoneos'
Error launching application on <设备名>
这个问题仅在使用 Android Studio 或 命令行构建 Flutter 项目 时发生,在 Xcode 中构建与运行一切正常。
📋 背景
- 项目中集成了 Apple Watch 应用(watchOS)相关 Targets ,包括:
Watch App
(com.apple.product-type.application.watchapp2
)WatchKit Extension
(com.apple.product-type.watchkit2-extension
)
- 这是 iOS 原生项目中常见的 watchOS 支持方式,属于完全合法的 Xcode target 配置。
- Flutter 项目使用的是 Flutter 3.32.7。
🧠 分析
Flutter CLI 工具在构建 iOS 项目时,底层使用了 xcodebuild
构建所有的 targets。而其中包含的 watchkit2-extension
和 watchapp2
类型的 target 并不被 Flutter CLI 完整支持 ,因而导致 xcodebuild
构建失败。
而在 Xcode 中运行时,IDE 能够智能地跳过这些不必要的 targets,因此不会报错。
📌 根因总结:
flutter_tools
默认解析并尝试构建所有 Xcode targets;- 当解析到
watchkit2-extension
相关 target 时,Flutter 无法识别这些 Product Type,构建失败; - 此问题不会在纯 iOS 项目或 Xcode 中出现,只影响通过 Flutter CLI 构建流程。
❓ 如何解决呢
-
找到 Flutter SDK 中的文件: packages/flutter_tools/lib/src/xcode_project.dart
xcode_project.dart 是 Flutter CLI 工具中用于解析 Xcode 工程(.xcodeproj)结构的核心模块,负责:
- 获取 Xcode targets 列表;
- 提取各 target 的构建设定(如 build settings, bundle id 等);
- 判断项目是否包含 Apple Watch companion target;
- 驱动构建流程根据 target 特性做出调整。
-
找到 xcode_project.dart 里的
containsWatchCompanion
方法它会遍历所有 targets,尝试读取 INFOPLIST_KEY_WKCompanionAppBundleIdentifier 值,并比对主 App 的 bundleIdentifier。
-
关键逻辑片段解释
这段逻辑说明:
- 如果某个 target 的 Info.plist 中设置了 WKCompanionAppBundleIdentifier;
- 且其值等于主 App 的 bundleIdentifier(或变量替换后一致);
- 则认为该工程包含 Watch companion app。
所以,Flutter 3.32.7 中的 flutter_tools 实际已经通过 xcode_project.dart 中的逻辑识别并处理 Apple Watch companion app 的存在。
✅ 解决
方式:配置 WKCompanionAppBundleIdentifier
✅ 步骤如下:
-
打开 Xcode,选择你的主 iOS App Target;
-
进入 TARGETS -> <你的 iOS App Target> -> Build Settings -> Info.plist Values;
-
设置(或确认存在)以下 Key:
- WatchKit Companion App Bundle Identifier
- Value 设置为你的 主 iOS App 的 Bundle ID(不是 Watch App 的 Bundle ID)
-
保存后,重新构建:
bashflutter clean flutter pub get flutter run