I have 100 images that I need to display in a list. I don't want to hard code all names.
How can I get the names of the images?
I want to have code like this:
final List<String> imageNames = await WhatEver.getNamesOfImagesInAssetsDirectory();
final widgets = imageNames.map((fileName) => Image.asset('images/${fileName}.png')).toList()
In Flutter, displaying an image can be done by using Image widget. Flutter provides a named constructor File. Image which can be used if the image source is from a file. Alternatively, you can also use FileImage .
I've implemented the function below inside of a StatefulWidget
Future _initImages() async {
// >> To get paths you need these 2 lines
final manifestContent = await rootBundle.loadString('AssetManifest.json');
final Map<String, dynamic> manifestMap = json.decode(manifestContent);
// >> To get paths you need these 2 lines
final imagePaths = manifestMap.keys
.where((String key) => key.contains('images/'))
.where((String key) => key.contains('.svg'))
.toList();
setState(() {
someImages = imagePaths;
});
}
AssetManifest.json
contains all data about all assets that you add in pubspec.yaml
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With