skip to Main Content

I’m using precacheImage in my app to load faster my assets. Despite this, my first screen images take less than a second to show, causing a bad user experience. I think that this happens because I’m calling precacheImage in the same screen where I have to show some of the images, but this i the very first screen of the app.
How can i avoid this behaviour? Is there a way to cache the images for the next app opens in order not to wait for them each time the user open the app?

2

Answers


  1. Nothing can happen if it is the first screen because you cannot call the method inside the main function as this requires a context object, you can show a loader to keep the user engaged. Or you can add a little splash screen that can buy you some time to load the image.

    Login or Signup to reply.
  2. or you can convert it into Image class from dart ui. you can load it first on loading screen, like a game.

    first you need specify you will use Image class from dart ui so:

    import 'dart.ui' as ui;
    

    everytime you want to use that Image class

    on loading.dart :

    Future<ui.Image> loadImage(String assetPath) async {
        ByteData data = await rootBundle.load(assetPath);
        ui.Codec codec = await ui.instantiateImageCodec(data.buffer.asUint8List());
        ui.FrameInfo fi = await codec.getNextFrame();
        return fi.image;
      }
    

    loading screen wait this function maybe you can warp with FutureBuilder :

    Future<ui.Image> _myfuture() async {
       ui.Image myImage = await loadImage('<your asset path>');
    }
    
    class myWidget extends StatelessWidget {
    ......
    return FutureBuilder(
           future: _myFuture
    )
    

    you can show it with CustomPainter or easy way is to use RawImage() class;

    RawImage(
                image: myImage,
              ),
    

    its will stay on memory forever you can assign it with your favorite State Management and call it everywhere.

    you dont use it anymore? dispose it. but remember it will not reusable after dispose:

    myImage.dispose()
    

    similiar case:

    before user play a game usually there is LoadingScreen everytime they want to play, and after current session is over, dispose it. and later he play another, load it again. you can imitate this bahavior into your own app

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search