Bryant Anthony
Bryant Anthony

Reputation: 135

How can I speed up the loading speed of my AssetImage?

My image size is quite small which is about 50kb but it seems to load longer than I expected it would be, so my app doesn't load up that prettily as I would imagined. Any way I could speed it up? `

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),
            ),
          ],
        ),
      ),
    );
  }
}

`

I tried compressing the image size which originally was 200 something kb to 50kb (current size) but it doesn't seem to do anything.

Upvotes: 3

Views: 1877

Answers (1)

Guillaume Roux
Guillaume Roux

Reputation: 7318

You can use the method 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,
          ),
        ),

        // ...
      ),
    );
  }
}

Upvotes: 1

Related Questions