I'm trying to build a GridView in Flutter that consists of about 20-30 hi-res images, but running into memory issues (with memory usage in the android studio profiler reaching up-to 1.2g, eventually leading to a blackout).
Here's how I'm building the 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
);
}
}
Apart from this implementation, I've also implemented a pagination mechanism to load just about 10 images at a time, then implemented the same thing using ListView.builder(), Even tried using GridView.count with cacheExtent set to 0
and addAutomaticKeepAlives to false
, and in all the cases the memory issue still persists.
Anyway I can resolve this problem? Thank You.