【问题标题】:Flutter How to get all files from assets folder in one ListFlutter 如何从一个 List 中的 assets 文件夹中获取所有文件
【发布时间】:2021-10-22 00:15:55
【问题描述】:

我在 assets 文件夹中有一堆 xml 文件,我添加了 pubspec.yaml 的路径,路径看起来像这样 'assets/data/somename.xml' 我需要从中获取数据,这就是我得到的方式现在就可以了

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

你怎么能看到我使用非常糟糕的方式从文件中获取数据, 将来会有更多的 xml 文件,所以我需要一些解决方案来解决这个问题,以便不在资产文件夹中的每个文件的 filePathList 中添加路径。 我还做了一个 loadData 函数来加载我想要的所有文件,但是我的 json 文件位于我使用 getApplicationDocumentDirectory 类获得的目录中。有代码

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();
    }
  }

如何在我的 getXmlData 函数中做这样的事情

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    在 pubspec 中只定义文件夹:

    assets:
     - assets/data/
    

    这将“加载”data 文件夹中的所有文件。

    并使用此代码:

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

    并使用过滤器获取所有xml 文件。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-17
      • 1970-01-01
      • 1970-01-01
      • 2018-02-20
      • 2013-11-26
      • 2013-06-09
      • 1970-01-01
      • 2020-03-03
      相关资源
      最近更新 更多