Pagrate
Pagrate

Reputation: 151

How do I preload images from assets?

I am trying to preload some assets that are used in a PageView like this..

  @override
  void didChangeDependencies() {
    precacheImage(AssetImage("assets/images/background.png"), context)
      .then((result) {
        print('$result');
      });

    super.didChangeDependencies();
  }

Expected result: The result value in then() would return the preloaded image Actual result: The result value is null

Does anyone have any examples of how preloadCache() is meant to work as the documentation for it is very poor

Upvotes: 1

Views: 2868

Answers (1)

Ringil
Ringil

Reputation: 6537

The return value for precacheImage is Future<void> so using then on the result will not return the image itself.

One of the easier ways to use it is to use in the build method of the parent widget of widget that you want to show the image like this:

class ImagePage extends StatelessWidget{   
  @override
  Widget build(BuildContext context) {
    return Image.network("https://upload.wikimedia.org/wikipedia/commons/3/39/Periodic_table_large.png");
  }
}

Then, you can call precacheImage in the widget before you navigate to the ImagePage like such:

class TestWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    precacheImage(NetworkImage("https://upload.wikimedia.org/wikipedia/commons/3/39/Periodic_table_large.png"), context);
    return Center(
          child: RaisedButton(
        child: Text('Launch screen'),
        onPressed: () {
          Navigator.push(
            context,
            MaterialPageRoute(builder: (context) => ImagePage()),
          );
        },
      ));
  }
}

This way when you press the button to launch the ImagePage, the image will already be loaded.

Upvotes: 3

Related Questions