本文介绍了Flutter:如何获取“资产”目录中所有图像的名称列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要在列表中显示100张图像。我不想对所有名称进行硬编码。
I have 100 images that I need to display in a list. I don't want to hard code all names.
如何获取图像名称?
我想要这样的代码:
final List<String> imageNames = await WhatEver.getNamesOfImagesInAssetsDirectory();
final widgets = imageNames.map((fileName) => Image.asset('images/${fileName}.png')).toList()
推荐答案
我已经在 StatefullWidget
内部实现了以下功能
I've implemented the function below inside of a StatefullWidget
Future _initImages() async {
// >> To get paths you need these 2 lines
final manifestContent = await DefaultAssetBundle.of(context).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
包含有关您添加到 pubspec.yaml
这篇关于Flutter:如何获取“资产”目录中所有图像的名称列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!