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

Flutter Web引擎加载时如何实现带准确百分比的进度条?

Flutter Web带加载百分比进度条实现方案

实现原理

Flutter 2.10+ 版本的Web编译产物提供了原生的加载进度监听钩子,可以直接获取核心资源(引擎、main.dart.js等)的加载进度,配合自定义的DOM结构即可实现类似Unity WebGL的进度条效果。

操作步骤

1. 新增加载占位DOM结构

打开项目web/index.html文件,在<body>标签内添加进度条相关的占位元素,示例代码如下:

<!-- 加载容器 -->
<div id="loading-container" style="display: flex; flex-direction: column; align-items: center; justify-content: center; height: 100vh; width: 100vw; background-color: #1a1a1a;">
  <!-- 替换为你自己的游戏logo -->
  <img src="icons/Icon-192.png" alt="游戏logo" style="width: 128px; margin-bottom: 32px;">
  <!-- 进度条容器 -->
  <div id="progress-bar-container" style="width: 300px; height: 8px; background-color: #333; border-radius: 4px; overflow: hidden;">
    <div id="progress-bar-fill" style="height: 100%; width: 0%; background-color: #2196F3; transition: width 0.1s ease;"></div>
  </div>
  <!-- 百分比文本 -->
  <p id="progress-text" style="color: #fff; margin-top: 16px; font-size: 14px;">0%</p>
</div>

2. 接入Flutter加载进度监听

找到index.html中原有Flutter加载的代码段,替换为带进度监听的逻辑:

<script>
  var loadingContainer = document.querySelector('#loading-container');
  var progressBarFill = document.querySelector('#progress-bar-fill');
  var progressText = document.querySelector('#progress-text');

  window.addEventListener('load', function(ev) {
    _flutter.loader.loadEntrypoint({
      onProgress: function(progress) {
        // progress取值范围为0-1,转成百分比
        const percent = Math.round(progress * 100);
        progressBarFill.style.width = `${percent}%`;
        progressText.textContent = `${percent}%`;
      },
      onEntrypointLoaded: async function(engineInitializer) {
        const engine = await engineInitializer.initializeEngine();
        await engine.runApp();
        // 加载完成后隐藏进度条
        loadingContainer.style.display = 'none';
      }
    });
  });
</script>

3. 补充游戏资源加载进度(可选,针对Flame游戏场景)

上述进度仅为Flutter引擎的加载进度,若要包含Flame游戏内的图片、音频等资源加载进度,可在Flutter侧main.dart中做二次进度合并:

  • 给引擎加载阶段分配60%的权重,游戏资源加载阶段分配40%的权重
  • Flutter侧初始化Flame时监听资源加载进度,更新总进度后通过dart:js_util调用JS方法更新DOM的进度展示

效果示例

Unity在logo下方展示进度条

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 03:51:00