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

Flutter Web部署Firebase Hosting刷新时出现页面未找到问题

解决Flutter Web部署Firebase Hosting刷新页面404问题

问题原因

  1. 部署目录错误:当前firebase.json中hosting.source设为根目录.,但Flutter Web构建后的静态文件(包括index.html)默认生成在build/web目录,根目录下无index.html,导致Firebase Hosting找不到入口文件。
  2. 单页应用路由未配置重写:Flutter Web是单页应用,所有路由由客户端处理。刷新非根路径时,浏览器会向服务器请求对应路径的文件,服务器不存在该文件,因此返回404。

解决方案

步骤1:构建Flutter Web产物

先执行构建命令生成正确的静态文件:

flutter build web

执行后项目根目录会生成build/web文件夹,包含index.html及其他静态资源。

步骤2:修改firebase.json配置

更新hosting部分,指定正确部署目录并添加路由重写规则:

{
  "hosting": {
    "source": ".",
    "public": "build/web", // 指定静态文件所在目录
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**",
      "**/build/**/!(web)" // 忽略build下除web外的其他目录
    ],
    "frameworksBackend": {
      "region": "us-central1"
    },
    "rewrites": [ // 添加路由重写,所有请求指向index.html
      {
        "source": "**",
        "destination": "/index.html"
      }
    ]
  },
  "functions": [
    {
      "source": "functions",
      "codebase": "default",
      "ignore": [
        "node_modules",
        ".git",
        "firebase-debug.log",
        "firebase-debug.*.log",
        "*.local"
      ],
      "predeploy": [
        "npm --prefix \"$RESOURCE_DIR\" run lint"
      ]
    }
  ]
}

步骤3:重新部署应用

执行部署命令更新Firebase Hosting:

firebase deploy --only hosting

关键说明

  • public字段指定Firebase Hosting要部署的静态文件目录,指向Flutter构建后的build/web,确保服务器能找到index.html。
  • rewrites规则将所有请求转发到index.html,让Flutter客户端处理路由,解决刷新非根路径时的404问题。

内容的提问来源于stack exchange,提问作者Dylan Wain

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 21:51:01