【发布时间】: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