【问题标题】:Out of memory when loading images to a Flutter Gridview将图像加载到 Flutter Gridview 时内存不足
【发布时间】:2019-10-23 06:23:01
【问题描述】:

我正在尝试在 Flutter 中构建一个包含大约 20-30 个高分辨率图像的 GridView,但遇到了内存问题(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() 实现了同样的事情,甚至尝试使用带有 cacheExtent set to 0 和 @ 的 GridView.count 987654323@,在所有情况下,内存问题仍然存在。

无论如何我可以解决这个问题? 谢谢。

【问题讨论】:

  • 为什么在网格视图中使用高分辨率图像?您只需要适合盒子的像素数。您可以在他们自己的页面上加载高分辨率图像,以便仅使用该特定图像所需的内存。
  • 感谢您的评论,gridview 的真正用途是在应用程序中显示用户拍摄的图像,低分辨率图像在崩溃之前确实可以保持更长的时间,但我想要模拟使用 Pixel 相机的情况。如何显示图像的低分辨率图像?或者有什么方法可以一次可靠地显示大约 10 张图像(高分辨率或低分辨率)而不会崩溃?
  • 有什么更新吗?改进?
  • 任何更新??我有同样的问题吗?
  • 我建议生成低分辨率图像(缩略图)。这个问题很常见(不仅在移动设备中)。

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


【解决方案1】:

由于正在显示和缓存的图像是最有可能调整大小的全尺寸图像(仍占用大量内存),因此引发内存不足错误。我建议为您将显示的图像生成缩略图以节省内存。这个post 有很多有用的答案供您选择。

您是否有特定的用例需要构建一个网格来从头开始显示本地存储中的图像?如果没有,您可能需要考虑使用image_picker 插件,如果您只是将此功能用作图像选择器。

【讨论】:

    猜你喜欢
    • 2014-08-12
    • 1970-01-01
    • 1970-01-01
    • 2014-09-15
    • 1970-01-01
    • 1970-01-01
    • 2013-05-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多