如何加快AssetImage的加载速度?

问题描述 投票:0回答:2

我的图像尺寸非常小,约为 50kb,但加载时间似乎比我预期的要长,因此我的应用程序加载速度并不像我想象的那么好。有什么办法可以加快速度吗? `

import 'dart:async';
import 'package:egarment2/pages/home_page.dart';
import 'package:egarment2/sign_in.dart';
import 'package:flutter/material.dart';

class SplashScreen extends StatefulWidget {
  const SplashScreen({Key? key}) : super(key: key);

  @override
  State<SplashScreen> createState() => _SplashScreenState();
}

class _SplashScreenState extends State<SplashScreen> {
  @override

  // void initState() {
  //   super.initState();
  //   Timer(
  //     const Duration(seconds: 3),
  //     () {
  //       Navigator.pushReplacement(
  //         context,
  //         MaterialPageRoute(
  //           builder: (context) => HomePage(),
  //         ),
  //       );
  //     },
  //   );
  // }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        // color: const Color(0xFFf65d46),
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/bg.jpg'),
            fit: BoxFit.fill,
          ),
        ),
        width: MediaQuery.of(context).size.width,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Image.asset(
              'assets/images/logo.png',
              width: 75,
              height: 75,
            ),
            const SizedBox(
              height: 25,
            ),
            const Text(
              'E-Garment',
              style: TextStyle(
                  color: Colors.black,
                  fontWeight: FontWeight.bold,
                  fontSize: 30),
            ),
          ],
        ),
      ),
    );
  }
}

`

我尝试将最初 200 kb 左右的图像大小压缩到 50kb(当前大小),但似乎没有任何作用。

flutter image flutter-layout loading
2个回答
1
投票

可以使用方法

precacheImage
:

class _SplashScreenState extends State<SplashScreen> {
   final _image = AssetImage('assets/images/bg.jpg');

  @override
  void initState() {
    super.initState();
    precacheImage(_image, context);
    
    // Add your own initState code here
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    precacheImage(_image, context);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: _image,
            fit: BoxFit.fill,
          ),
        ),

        // ...
      ),
    );
  }
}

0
投票

但是如果你渲染多个图像我们该怎么办?

© www.soinside.com 2019 - 2024. All rights reserved.