将图像加载到Flutter Gridview时内存不足

时间:2019-06-07 18:20:26

标签: flutter dart out-of-memory flutter-gridview

我正在尝试在Flutter中构建一个GridView,其中包含约20-30个高分辨率图像,但是遇到内存问题(Android Studio Profiler中的内存使用量高达1.2g,最终导致停电)。

这是我构建GridView的方式,

@override
Widget build(BuildContext context) {
  return Scaffold(
    body: new SafeArea(
        child: new Center(
          child: _imageSectionFutureBuilder(), // <-- The core component
        )),
  );
}

Widget _imageSectionFutureBuilder() {
    // Pseudocode is as follows,
    return new FutureBuilder(
        future: _FetchImageLocationsFromDb().then(results) {
        // Some data pre-processing
        preProcessData(results);
    },
    builder: (context, snapshot){
        if (snapshot.hasData) {
        // Here's where I'm building the GridView Builder.
        return new GridView.builder(
          gridDelegate: new SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
          itemBuilder: (BuildContext context, int index) {
            return _getCurrentItem(snapshot.data[index]); // <-- This function loads a particular image
            }
          );
        } else {
        // Display a different widget saying no data is available.
          return _showNoDataWidget();
        }
      },
    );
  }

  Widget _getCurrentItem(String imagePath) {
    if (FileSystemEntity.typeSync(imagePath) != FileSystemEntityType.notFound) {
      File imageFile = new File(imagePath);
      return new Container(
          child: new Image.file(
            imageFile,
            fit: BoxFit.cover
          ) // <-- Box fitting to ensure specific height images to the gridview
      );
    }
  }

除此实现之外,我还实现了分页机制,一次仅加载约10张图像,然后使用ListView.builder()实现了相同的功能,甚至尝试将GridView.count与cacheExtent set to 0一起使用和addAutomaticKeepAlives to false,并且在所有情况下,内存问题仍然存在。

无论如何我都可以解决此问题? 谢谢。

0 个答案:

没有答案