Search code examples
flutterflutter-navigation

How to know if an Image is in memory in Flutter?


I have a screen in my app with an image as the background, this image is on my asset folder. When I navigate to this screen the background is blank for an instant and then the image is loaded and it appears. This makes my screen look weird for a half a second or less, but enough for the user to notice.

I wanted to be able to only navigate to that screen once the image is loaded (I can wait on the previous screen), so I can avoid this behavior and have the screen as a whole when the user navigates there.

I know can make the image fade in, but that's not the experience that I want.


Solution

  • You need to use ImageProvider.resolve method

    So suppose you have some image registered in you assets. Then you may obtain the image provider as

    _imageProvider = Image.asset("your_asset").image.

    Then you may add such method:

    import 'dart:ui';
    
    Image _image;
    bool _resolved;
    
    void _resolveImageProvider() {
        ImageStream stream = _imageProvider.resolve(createLocalImageConfiguration(context));
        stream.addListener(ImageStreamListener((info, _) {
          setState(() {
            //here you may set some flags or anything which indicates the image is in memory now.
            _resolved = true;
            _image = info.image;
          });
        }));
      }
    

    Then you can call this method on the "previous screen", wait till the listener is triggered and only then navigate to the next view.