Flutter How to get all files from assets folder in one List

Viewed 906

I have a bunch of xml files in assets folder, I add path to pubspec.yaml and path looks like this 'assets/data/somename.xml' I need to get data from them and this is the way how i got it now

List filePathList = ['assets/data/widow.xml','assets/data/door.xml'];
    for(int i = 0;i<filePathList.length;i++){
      var xmlFile =  XmlDocument.parse(await rootBundle.loadString(filePathList[i]));
      checkListtemplateXmlList.add(xmlFile);
}

How you can see i use realy bad way to take data from files, there will be many more xml files in the future so i need some solution to this problem to not add path in filePathList for every file in assets folder. Also i made a loadData function that load all files like i want, but my json files are in directory that i got with using getApplicationDocumentDirectory class. There is a code

static Future<void>  loadData() async {
    final dir = await getApplicationDocumentsDirectory();
    List<FileSystemEntity> files = await dir.list().toList();
    for (int i = 0; i < files.length; i++) {
      String filepath = files[i].path;
      File newFile = File(filepath);
      String name = p.basenameWithoutExtension(newFile.path);
      String myExtension = p.extension(filepath);
      if(myExtension != '.json'){
      } else{
        checkLists.add(CheckList(name));
      }
    }
    for(int i = 0;i< checkLists.length;i++){
      await checkLists[i].readFile();
    }
  }

how i can do something like this in my getXmlData function

1 Answers

Inside the pubspec define only the folder:

assets:
 - assets/data/

This will "load" all files inside the data folder.

And using this code:

// This will give a list of all files inside the `assets`.
var assets = await rootBundle.loadString('AssetManifest.json');

And use a filter to get all xml files.

Map json = json.decode(assets);
List get = json.keys.where((element) => element.endsWith(".xml")).toList();
Related