flutter WEB端启动优化(加载速度,加载动画)

Flutter WEB端的开发者可能都面临过一个共同的问题:由于需要加载大量的配置文件,启动速度相对较慢。

以下是针对这一问题的一些优化策略,旨在帮助开发者提升应用的加载速度。

一. 压缩加载资源

加载自定义字体和图片等资源往往会影响启动速度。以下是一些压缩资源的方法:

  1. 压缩图片资源:适当减小图片文件的大小。
  2. 优化字体资源:提取字体中的常用文字,创建一个小型的字体包,并在加载完成后异步加载完整字体包进行替换。
  • 步骤1 :创建一个包含常用文字的data.json文件。
  • 步骤2 :使用Python的fontTools库,根据data.json生成压缩后的字体文件。
python 复制代码
#!/usr/bin/python
# coding=UTF-8

import json
from fontTools import subset

def generate(source_font, json_file, out_file):
    all_chars = []
    checker = {}
    with open(json_file, 'r', encoding='utf-8') as f:
        text_data = json.load(f)
        elements = text_data['elements']

        for element in elements:
            value = element['text']
            for char in value:
                uid = ord(char)
                if uid not in checker:
                    checker[uid] = True
                    all_chars.append(char)

    text = ''.join(all_chars)
    font = subset.load_font(source_font, subset.Options())
    subsetter = subset.Subsetter()
    subsetter.populate(text=text)
    subsetter.subset(font)
    subset.save_font(font, out_file, subset.Options())
    font.close()

if __name__ == '__main__':
    source_font = "./alipuhui-3-55.ttf"
    json_file = "./data.json"
    out_file = "picked.ttf"
    generate(source_font, json_file, out_file)
  • 步骤3 :在pubspec.yml中添加字体文件,并在代码中初始化时使用压缩字体,待完整字体加载完成后替换。
dart 复制代码
String customFont = '阿里普惠shrink';

loadFont() async {
    var bundle = await rootBundle.load('assets/fonts/alipuhui-3-55.ttf');
    var loader = FontLoader('阿里普惠')..addFont(Future.value(bundle));
    await loader.load();
    customFont = '阿里普惠';
    if (mounted) setState(() {});
}

二. 网络字体(google字体)使用国内cdn

如果网络资源使用的是外网地址或国外CDN,加载速度可能会受到影响。建议使用国内CDN或移除这些资源。

三. 声明延迟导入

将代码拆分,仅在需要时加载相应的代码块,可以有效减少初始加载时间。

四. 优化首屏加载动画

index.html中添加加载动画,并在首屏加载完成后移除。

html 复制代码
<!DOCTYPE html>
<html>
<head>
    <!-- 省略... -->
</head>
<body>
    <!-- Loading indicator -->
    <style>
        .container{
            width: 100vw;
            height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            flex: auto;
            flex-direction: column;
        }
        .indicator{
            width: 100px;
            height: 100px;
            margin-bottom: 15px;
        }
        .progress-bar {
            width: 100px;
            background-color: #f3f3f3;
            border-radius: 4px;
        }
        @keyframes progress {
            0% { width: 50%; }
            100% { width: 100%; }
        }
        .progress-bar-fill {
            display: block;
            height: 5px;
            background-color: #46494b;
            border-radius: 4px;
            transition: width 0.2s ease-in;
            animation: progress 5s ease-in-out forwards;
        }
    </style>
    
    <div id="loading_indicator" class="container">
        <img class="indicator" src="icons/icon-192.png"/>
        <div class="progress-bar">
            <div class="progress-bar-fill" style="width: 50%;"></div>
        </div>
    </div>
    <script>
        window.addEventListener('load', function(ev) {
            var loading = document.getElementById('loading_indicator');
            _flutter.loader.loadEntrypoint({
                serviceWorker: {
                    serviceWorkerVersion: serviceWorkerVersion,
                },
                onEntrypointLoaded: async function(engineInitializer) {
                    let appRunner = await engineInitializer.initializeEngine();
                    await appRunner.runApp();
                    window.setTimeout(function () {
                        loading.remove();
                    }, 200);
                }
            });
        });
    </script>
</body>
</html>

五. 使用Wasm渲染

从Flutter 3.22版本开始,Wasm渲染方式得到了支持。与CanvasKit相比,Wasm不仅减小了应用程序的大小,而且启动速度更快。不过,目前Wasm还处于实验阶段,建议在稳定支持后再进行使用。

六. 使用AppUploader简化发布流程

在完成Flutter WEB应用优化后,如果你还需要开发iOS版本,可以考虑使用AppUploader这款iOS开发助手工具。它能帮助你:

  1. 快速生成iOS应用的描述文件
  2. 简化证书管理流程
  3. 提供一键式打包和上传功能

AppUploader特别适合需要同时维护WEB和移动端的开发者,可以节省大量在证书配置和发布流程上的时间。

希望以上优化策略能够帮助你开发出既完善又快速响应的WEB应用。

相关推荐
Hello.Reader1 小时前
洞悉 NGINX ngx_http_access_module基于 IP 的访问控制实战指南
tcp/ip·nginx·http
高效匠人3 小时前
FastAPI + Redis Pub/Sub + WebSocket 组合解决方案的详细介绍
redis·websocket·fastapi
CyberSecurity_zhang3 小时前
汽车网络安全 -- 理解暴露面、攻击面和攻击向量
网络安全·信息安全·汽车
SQingL4 小时前
解决SSLError: [SSL: DECRYPTION_FAILED_OR_BAD_RECORD_MAC] decryption faile的问题
服务器·网络协议·ssl
JhonKI5 小时前
【Linux网络】构建与优化HTTP请求处理 - HttpRequest从理解到实现
linux·网络·http
技术liul6 小时前
如何在iStoreOS DHCP中排除特定IP地址
网络·windows·tcp/ip
网工养成记_121387 小时前
路由协议基础
网络·网络协议·智能路由器
JhonKI7 小时前
【Linux网络】Http服务优化 - 增加请求后缀、状态码描述、重定向、自动跳转及注册多功能服务
linux·网络·http
〆、风神8 小时前
从零实现分布式WebSocket组件:设计模式深度实践指南
分布式·websocket·设计模式
茉莉玫瑰花茶8 小时前
socket套接字-UDP(中)
网络·网络协议·udp