Check if asset exists

时间:2018-06-04 17:02:10

标签: file dart try-catch flutter assets

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 个答案:

答案 0 :(得分:3)

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 {
      data = await rootBundle.loadString(path);
    } catch(_) {
      return null;
    }
  } 
var assetPaths = ['file1path', 'file2path', 'file3path'];
var asset;

for(var assetPath in assetPaths) {
  asset = myLoadAsset(assetPath);
  if(asset != null) {
    break; 
  }
}

if(asset == null) {
  throw "Asset and fallback assets couldn't be loaded";
}