I have an assets folder in which I have a tab folder and then a list of folders and each folder contains some files:
I want to read the names of all the files and folders that are in my assets folder. How do I do that?
I have an assets folder in which I have a tab folder and then a list of folders and each folder contains some files:
I want to read the names of all the files and folders that are in my assets folder. How do I do that?
Even if you specified only asset folders in pubspec.yaml
, the flutter compiler lists all files from these folders in AssetManifest.json
file. All we have to do is read this file:
final manifestJson = await DefaultAssetBundle.of(context).loadString('AssetManifest.json');
final images = json.decode(manifestJson).keys.where((String key) => key.startsWith('assets/images'));
final manifestJson = await rootBundle.loadString('AssetManifest.json')
–
Esp The easiest way to do this is, open your pubspec.yaml and in the assets line, change it as given below - just add the entire folder.
assets:
- assets/
This will add all the folders and files in the asset folders.
assets: - assets/
it get all the files without * as well. This only allows an asset to be used in your app. Still we have to know each file and directory name and hard code them into our code. What I want is I want an iterative solution i.e. i don't know how many files or folders are there in assets folder just get all file paths and show all files in a list. –
Mezzanine I've got same issue,
As of sep 2021, there is still no way to get all the assets without manually listing it in pubspec.yaml
before calling
final manifestJson = await DefaultAssetBundle.of(context).loadString('AssetManifest.json');
However there is workaround, if you are using Android Studio/IntelliJ You can install https://plugins.jetbrains.com/plugin/13629-flutter-assets-ref-generator
Then you can use it to list all your assets files into pubspec.yaml
with one click of button.
It solve the problem for me.
According to the Flutter Official, they now provide the common way to insert all the files in the directories.
flutter:
assets:
- directory/
- directory/sub_directory/
ref : https://docs.flutter.dev/development/ui/assets-and-images
Spatz's answer is correct, however you don't always have context
available.
In those cases, you can use rootBundle
:
final manifestJson = await rootBundle.loadString('AssetManifest.json');
final images = json.decode(manifestJson).keys.where((String key) => key.startsWith('assets/images'));
© 2022 - 2024 — McMap. All rights reserved.
assets: - assets/
to get all files available for use in my code. Now I need each file path in a list or map without hard coding them in my code, so that I can iterate through them and show them in a ListView. Thanks – Mezzanine