You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter Web应用无法在Firebase Hosting打开的解决求助

Flutter Web部署Firebase Hosting异常排查与解决

问题描述

用Flutter开发了一个简单Web应用,部署到Firebase Hosting后无法正常打开。修改index.html、调整索引路径后出现_flutter is not defined错误,清理后又出现新错误。网站链接:https://triyingweb.web.app/

提供的文件内容

index.html代码

<html>
<head>
  <!--
    If you are serving your web app in a path other than the root, change the
    href value below to reflect the base path you are serving from.

    The path provided below has to start and end with a slash "/" in order for
    it to work correctly.

    For more details:
    * https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base

    This is a placeholder for base href that will be replaced by the value of
    the `--base-href` argument provided to `flutter build`.
  -->
  <base href="./">

  <meta charset="UTF-8">
  <meta content="IE=Edge" http-equiv="X-UA-Compatible">
  <meta name="description" content="A new Flutter project.">

  <!-- iOS meta tags & icons -->
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black">
  <meta name="apple-mobile-web-app-title" content="sdk_flutter_2">
  <link rel="apple-touch-icon" href="icons/Icon-192.png">

  <!-- Favicon -->
  <link rel="icon" type="image/png" href="favicon.png"/>

  <title>sdk_flutter_2</title>
  <link rel="manifest" href="manifest.json">

  <script>
    // The value below is injected by flutter build, do not touch.
    const serviceWorkerVersion = null;
  </script>
  <!-- This script adds the flutter initialization JS code -->
  <script src="/main.dart.js" defer></script>
</head>
<body data-new-gr-c-s-check-loaded="14.1113.0" data-gr-ext-installed="">
<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/7.15.1/firebase-app.js"></script>

<!-- TODO: Add SDKs for Firebase products that you want to use
   https://firebase.google.com/docs/web/setup#available-libraries -->
<script src="https://www.gstatic.com/firebasejs/7.15.1/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.15.1/firebase-firestore.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.15.2/firebase-storage.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.15.1/firebase-analytics.js"></script>


<!-- This script installs service_worker.js to provide PWA functionality to
     application. For more information, see:
     https://developers.google.com/web/fundamentals/primers/service-workers -->
<script>
 if ('serviceWorker' in navigator) {
    window.addEventListener('sw-cached-site.js', function() {
      navigator.serviceWorker.register('service-worker.js', {
        scope: '/',
      });
    });
  }
  window.process = { env: { NODE_ENV: 'production' } };
  </script>
<script src="main.dart.js" type="application/javascript"></script>


</body>
<script>
  <script>
  // Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getAnalytics } from "firebase/analytics";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries

// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
  apiKey: "AIzaSyCYgkDBNvQukJaCvit3lH8vpY8ISi1ld7I",
  authDomain: "triyingweb.firebaseapp.com",
  projectId: "triyingweb",
  storageBucket: "triyingweb.appspot.com",
  messagingSenderId: "778280603165",
  appId: "1:778280603165:web:f7752b68d3d4b7348440f4",
  measurementId: "G-5D0GNTWXBS"
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);

</script>
</html>

firebase.json代码

{
  "hosting": {
    "public": "web",
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ],
    "rewrites": [
      {
        "source": "**",
        "destination": "/index.html"
      }
    ]
  }
}

解决方案

1. 修复index.html的核心问题

  • 删除重复的main.dart.js引入:代码中同时存在<script src="/main.dart.js" defer></script>和<script src="main.dart.js" type="application/javascript"></script>,保留前者即可,避免初始化冲突。
  • 统一Firebase SDK版本与引入方式:混用v7.15.1和v7.15.2版本的Firebase SDK会导致兼容性问题,统一为同一版本;同时不要混用全局script引入和ES模块import,二选一:
    • 选全局引入:删除所有import代码,改用firebase.initializeApp(firebaseConfig)初始化
    • 选ES模块:替换所有script标签为模块形式,比如将Firebase初始化代码放入单独的js文件,用<script type="module" src="firebase-init.js"></script>引入
  • 修复Service Worker监听逻辑:window.addEventListener('sw-cached-site.js', ...)是错误写法,应监听load事件:
    if ('serviceWorker' in navigator) {
      window.addEventListener('load', function() {
        navigator.serviceWorker.register('service-worker.js', { scope: '/' });
      });
    }
    
  • 清理嵌套的script标签:最后一段Firebase初始化代码存在嵌套的<script>标签,删除外层多余标签,保证HTML结构合法。

2. 修正Flutter构建与Firebase配置

  • 执行正确的构建命令(部署到根路径需指定--base-href "/"):
    flutter build web --base-href "/"
    
  • 调整firebase.json的public字段:Flutter Web构建产物默认在build/web目录,因此将"public": "web"改为"public": "build/web",确保Firebase能找到正确的部署文件。

3. 重新部署流程

  1. 清理旧构建产物:flutter clean
  2. 重新构建Web应用:flutter build web --base-href "/"
  3. 确认Firebase CLI已登录:firebase login
  4. 部署到Firebase Hosting:firebase deploy --only hosting

内容的提问来源于stack exchange,提问作者Berkay Isıkoglu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 05:54:58