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

Flutter Web构建Release版本后页面白屏问题求助

Flutter Web构建后Python HTTP服务器白屏问题解决

问题现象

在pubspec.yaml所在目录执行flutter build web --release完成构建后,进入build/web目录,通过python -m http.server 5000启动HTTP服务器,网页显示空白白屏。浏览器开发者工具日志报错:

The script has an unsupported MIME type ('text/plain').
localhost/:1 Uncaught (in promise) DOMException: Failed to register a ServiceWorker for scope ('http://localhost:5000/') with script ('http://localhost:5000/flutter_service_worker.js?v=3443120066'): The script has an unsupported MIME type ('text/plain').

Python服务器控制台日志:

Serving HTTP on :: port 5000 (http://[::]:5000/) ...
::1 - - [30/Jul/2022 01:01:58] "GET / HTTP/1.1" 304 -
::1 - - [30/Jul/2022 01:01:58] "GET /flutter.js HTTP/1.1" 304 -
::1 - - [30/Jul/2022 01:01:59] code 404, message File not found
::1 - - [30/Jul/2022 01:01:59] "GET /requestProvider.js.map HTTP/1.1" 404 -
::1 - - [30/Jul/2022 01:01:59] "GET /flutter_service_worker.js?v=3443120066 HTTP/1.1" 200 -
::1 - - [30/Jul/2022 01:02:03] "GET /main.dart.js HTTP/1.1" 304 -
::1 - - [30/Jul/2022 01:02:03] "GET /main.dart.js.map HTTP/1.1" 200 -
::1 - - [30/Jul/2022 01:02:04] code 404, message File not found
::1 - - [30/Jul/2022 01:02:04] "GET /main.dart HTTP/1.1" 404 -

原因分析

Python自带的http.server模块默认对.js文件的MIME类型识别为text/plain,但Service Worker规范要求注册脚本必须返回application/javascript类型,导致浏览器拒绝加载Service Worker,进而引发Flutter Web应用无法正常初始化,出现白屏。

解决方法

方法1:使用自定义Python服务器脚本指定MIME类型

在build/web目录下创建一个server.py文件,内容如下:

from http.server import HTTPServer, SimpleHTTPRequestHandler
import mimetypes

class CustomHandler(SimpleHTTPRequestHandler):
    def guess_type(self, path):
        if path.endswith('.js'):
            return 'application/javascript'
        return super().guess_type(path)

if __name__ == '__main__':
    HTTPServer(('', 5000), CustomHandler).serve_forever()

然后执行以下命令启动服务器:

python server.py

方法2:使用npm的serve工具(推荐)

  1. 确保已安装Node.js和npm
  2. 全局安装serve工具:
npm install -g serve
  1. 在build/web目录下执行:
serve -l 5000

serve会自动正确处理所有静态文件的MIME类型,无需额外配置。

方法3:修改Python全局MIME类型配置(不推荐)

找到Python安装目录下的mime.types文件(通常在Lib/mimetypes.py或etc/mime.types),添加或修改以下行:

application/javascript js

修改后重启Python服务器即可。但此方法会影响所有使用http.server的Python程序,不建议在共享环境中使用。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 15:27:49