Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix Listview scrolling jank when loading images from network

Tags:

flutter

I am loading images using Image.network for each item in a list using the following code:

Image getEventImageWidget(AustinFeedsMeEvent event) {
return event.photoUrl.isNotEmpty ?
          Image.network(
            event.photoUrl,
            width: 77.0,
            height: 77.0,
          ) : Image.asset(
            'assets/ic_logo.png',
            width: 77.0,
            height: 77.0,
          );
}

When I scroll up and down, the list sometimes hangs when loading the images. Is there a way I can load the images on a background thread? What can I do to help fix scrolling performance?

NOTE: When I looked back at this, I found that the images that I was using were really large.

like image 413
dazza5000 Avatar asked Jul 09 '18 02:07

dazza5000


2 Answers

There are two was to speed up the rendering of your ListView of images.

The first is to set the cacheExtent property to a larger value in your ListView constructor. This property controls how much offscreen widgets are rendered, and will help by causing the rendering to start a bit sooner.

The second is to pre-cache your images using precacheImage. Flutter has an in-memory cache, so it is generally to necessary to cache everything to disk to get good read performance. Instead, you can ask Flutter to download these images ahead of time so that they are ready when the widget is built. For example, if you have a list of urls of your image, then in an initState method you could ask Flutter to cache all of them.

final List<String> imageUrls = [ /* ... */ ];

@override
void initState() {
  for (String url in imageUrls) {
    precacheImage(new NetworkImage(url), context);
  }
  super.initState();
}
like image 157
Jonah Williams Avatar answered Nov 02 '22 11:11

Jonah Williams


Are you sure your images are not very heavy? Check the size of the images first. Also you can use the package named: cache_network_image

It's very simple :

new Image(image: new CachedNetworkImageProvider(url))

UPDATE (Package was updated)

CachedNetworkImage(
        imageUrl: "http://via.placeholder.com/350x150",
        placeholder: (context, url) => new CircularProgressIndicator(),
        errorWidget: (context, url, error) => new Icon(Icons.error),
     ),
like image 34
diegoveloper Avatar answered Nov 02 '22 10:11

diegoveloper