Flutter read all files from asset folder

5,339

Solution 1

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'));

Solution 2

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.

Share:
5,339
Taha Malik
Author by

Taha Malik

Enthusiast Java-EE and Android Developer

Updated on December 15, 2022

Comments

  • Taha Malik
    Taha Malik over 1 year

    I have an assets folder in which I have a tab folder and then a list of folders and each folder contains some files

    enter image description here

    Now I want to read the names of all the folders that are in the tabs folder and all the files that are in each subfolder of the tabs folder, i.e. folders that are named as sound 1, sound 2, sound 3 .....

    In simple words, I want to read names of all files and folders that are in my assets folder. Please Anyone help. Thanks,

  • Taha Malik
    Taha Malik over 4 years
    I was doing : 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.
  • Taha Malik
    Taha Malik almost 4 years
    I tried that but it seems like this file contains information that we enter in pubspec.yaml. So, I don't want to enter all asset names in the manifest.
  • Spatz
    Spatz almost 4 years
    @Taha Malik You have to place only folder names (with trailing slash) in pubspec.yaml, not an asset file names.
  • zap
    zap over 2 years
    can use by this way without context final manifestJson = await rootBundle.loadString('AssetManifest.json')