MG lolenstine
MG lolenstine

Reputation: 969

Flutter: Display a large amount of images without OOM

I'm trying to make a book reader, which would allow you to read only one book. This book has limited amount of pages(228), and I have urls to every page.

Now, I'm trying to display all of the images in the ListView, but it loads all images at once, and they're over 1GB in size, so the app crashes, saying out of memory error.

How would I free memory of the invisible items in the ListView and then load them again upon scrolling back to it?

My current code for building the LinearView is as following

new Scaffold(
        appBar: new AppBar(
          title: new Text(widget.title),
        ),
        body: new ListView.builder(
          padding: new EdgeInsets.all(8.0),
          itemBuilder: (BuildContext context, int index) {
            return new Image.network(MyApp.imageLinks.values.elementAt(index));
          },),
        // This trailing comma makes auto-formatting nicer for build methods.
      );

But as I said, it throws an OOM error.

My device has 3GB of HW ram, which is not enough.

Thanks in advance.

Upvotes: 2

Views: 3222

Answers (1)

MαπμQμαπkγVπ.0
MαπμQμαπkγVπ.0

Reputation: 6729

Try to have a look at the package extended_image.

A powerful official extension library of image, which support placeholder(loading)/ failed state, cache network, zoom pan image, photo view, slide out page, editor(crop,rotate,flip), paint custom etc.

You can also check out this documentation about "Loading images":

Flutter can load resolution-appropriate images for the current device pixel ratio.

This idea was taken from this SO post which I think the same case on you.

If you are fetching your images from network which is more likely, make sure their sizes are appropriate, and have different sizes served if you can. If you don't have control over that set cacheWidth and cacheHeight in Image.memory these will reduce the cached image in memory (RAM). You see by default Flutter caches images in full resolution despite their apparent size in the device/app. For example if you want your image to display in 200x200 box then set cacheWidth to 200 * window.devicePixelRatio.ceil() you will find window in dart:ui, and if you only set cacheWidth, the ratio of your images will remain true. Same true if you only set cacheHeight. Also do use ListView.builder as suggested.

Upvotes: 2

Related Questions