How to get rid of load times for asset images in flutter

Viewed 273

I am building an app that uses lots of images and I was wondering if there is a way to get rid of the time it takes for the image to load and show up on screen when the image is being called? Here is a simple example of an image that I want to be loaded that is contained inside of a visibility widget.

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(),
    );
  }
}

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

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  bool isVis = false;

  Widget _showAssetImage() {
    return Visibility(
      visible: isVis,
      child: Container(
        width: 100,
        height: 100,
        decoration: BoxDecoration(
            color: Colors.amber,
            image: DecorationImage(image: AssetImage('deer.jpg'))),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: Text('test app'),
      ),
      body: _showAssetImage(),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.image),
        onPressed: () {
          setState(() {
            isVis = true;
          });
        },
      ),
    );
  }
}
1 Answers

you can try precacheImage():

  final theImage = Image.asset("deer.jpg");

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

use it with:

  Container(
    width: 100,
    height: 100,
    child: theImage,
  ),
Related