Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preloading local image assets in Flutter

Tags:

flutter

dart

I have a list of image assets, and I have one Image widget onscreen. I use a button to cycle through them, using setState().


    const List<String> _photoData = const [
      "assets/generic-cover.jpg",
      "assets/generic-cover2.jpg",
      "assets/generic-cover3.jpg",
      "assets/generic-cover4.jpg",
    ];

    class _MyHomePageState extends State<MyHomePage> {

      int _coverPhoto = 0;

      void _switchCoverPhoto() {
        setState(() {
          _coverPhoto++;
          if (_coverPhoto == _photoData.length) {
             _coverPhoto = 0;
          }
        });
      }

      @override
      Widget build(BuildContext context) {

        return new Scaffold(
          body: new Stack(
            children: <Widget>[
              new Image.asset (
                _photoData[_coverPhoto],
                fit: ImageFit.cover,
                height: 600.0,
              ),
              new Positioned ( // photo toggle button
                child: new IconButton(
                  icon: new Icon (Icons.photo),
                  onPressed: _switchCoverPhoto,
                  color: Colors.white,
                ),
                top: 32.0,
                right: 32.0,
              ),
            ]
          )
        );
      }

The first image renders fine. However, when I call _switchCoverPhoto(), there's a brief white flash before "assets/generic-cover2.jpg" gets shown.

Which leads to a simple question: Is there an easy way to preload a subsequent image (or images) into memory, so that there's no flash beforehand?

See attached GIF for a loose approximation.

like image 553
bkobash Avatar asked Jan 05 '17 00:01

bkobash


1 Answers

Make sure you have gaplessPlayback set to true for your image.

This won't solve the preloading problem, but it will prevent the image from flashing to white when switching assets.

With gaplessPlayback set to true, your original image will remain until the new image has completed loading and no "white flash gap" will be present.

var img = new Image.asset(
  _photoData[_coverPhoto],
  fit: ImageFit.cover,
  height: 600.0,
  gaplessPlayback: true,
);
like image 163
Dvdwasibi Avatar answered Nov 07 '22 20:11

Dvdwasibi