Check if asset exists

十年热恋 提交于 2020-04-11 04:19:08

问题


Is there any way to check if a asset file exists in Flutter before try to load the data?

For now I have the following:

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

The problem is, that I have to check for file 1, if this does not exits I have to check for a fallback file (file 2) and if this does also not exist I load a third file.

My complete code would look like this:

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

That looks very ugly to me, but I have no better idea...


回答1:


AssetBundle (as returned by rootBundle) abstracts over different ways of loading assets (local file, network) and there is no general way of checking if it exists.

You can easily wrap your loading code so that it becomes less "ugly".

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


来源:https://stackoverflow.com/questions/50685492/check-if-asset-exists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!