Flutter Web构建后Firebase.initializeApp报错求助
当执行flutter build web构建Web应用后,调用Firebase.initializeApp()时出现以下错误:
VM86:2 Uncaught (in promise) TypeError: Failed to resolve module specifier 'Instance of 'TrustedScriptURL''
at window.ff_trigger_firebase_core (:2:18)VM87:2 Uncaught (in promise) TypeError: Failed to resolve module specifier 'Instance of 'TrustedScriptURL''
at window.ff_trigger_firebase_app_check (:2:18)VM88:2 Uncaught (in promise) TypeError: Failed to resolve module specifier 'Instance of 'TrustedScriptURL''
at window.ff_trigger_firebase_remote_config (:2:18)VM89:2 Uncaught (in promise) TypeError: Failed to resolve module specifier 'Instance of 'TrustedScriptURL''
at window.ff_trigger_firebase_firestore (:2:18)
但使用flutter run运行应用时一切正常,以下是可行的解决方案:
降级Firebase相关依赖版本
这个问题多是Firebase Flutter插件新版本与Web构建流程不兼容导致的。尝试将相关依赖降级到稳定版本,在pubspec.yaml中修改:firebase_core: ^2.15.0 firebase_app_check: ^0.2.1+3 firebase_remote_config: ^4.2.0 cloud_firestore: ^4.8.4修改后执行
flutter pub get拉取依赖,再重新构建Web应用。禁用Trusted Types支持
部分浏览器环境或构建配置下,Trusted Types处理会异常。在web/index.html中添加以下脚本(放在Firebase SDK引入脚本之前):<script> if (typeof trustedTypes !== 'undefined') { trustedTypes.createPolicy('default', { createScriptURL: (url) => url, createScript: (script) => script, createHTML: (html) => html }); } </script>切换到Flutter稳定版
避免使用dev或beta分支的Flutter SDK,执行以下命令切换并更新:flutter channel stable flutter upgrade清理构建缓存后重新构建
缓存异常也可能引发问题,执行以下命令清理后重新构建:flutter clean flutter pub get flutter build web
内容的提问来源于stack exchange,提问作者Marco Canuto

