【问题标题】:Check if asset exists检查资产是否存在
【发布时间】:2018-11-14 01:53:37
【问题描述】:

在尝试加载数据之前,有什么方法可以检查 Flutter 中是否存在资产文件?

现在我有以下内容:

String data;
try {
  data = await rootBundle
      .loadString('path/to/file.json');
} catch (Exception) {
  print('file not found');
}

问题是,我必须检查文件 1,如果它不存在,我必须检查备用文件(文件 2),如果它也不存在,我会加载第三个文件。

我的完整代码如下所示:

try{
  //load file 1
} catch (..) {
  //file 1 not found
  //load file 2
} catch (...) {
  //file 2 not found
  //load file 3
}

这对我来说看起来很丑陋,但我没有更好的主意......

【问题讨论】:

    标签: file dart try-catch flutter assets


    【解决方案1】:

    AssetBundle(由rootBundle 返回)抽象了加载资产(本地文件、网络)的不同方式,没有通用的方法来检查它是否存在。

    您可以轻松包装加载代码,使其变得不那么“丑陋”。

      Future myLoadAsset(String path) async {
        try {
          return await rootBundle.loadString(path);
        } catch(_) {
          return null;
        }
      } 
    
    var assetPaths = ['file1path', 'file2path', 'file3path'];
    var asset;
    
    for(var assetPath in assetPaths) {
      asset = await myLoadAsset(assetPath);
      if(asset != null) {
        break; 
      }
    }
    
    if(asset == null) {
      throw "Asset and fallback assets couldn't be loaded";
    }
    

    【讨论】:

    • 此代码似乎无效,因为myLoadAsset 始终返回非空值。毕竟你没有await
    猜你喜欢
    • 2015-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多