Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if asset exists

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...

like image 890
T R Avatar asked Jun 04 '18 17:06

T R


1 Answers

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";
}
like image 95
Günter Zöchbauer Avatar answered Oct 17 '22 12:10

Günter Zöchbauer