Check if asset exists

7,069

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";
}
Share:
7,069
T R
Author by

T R

Webdeveloper with skills in Java, C#, Python, Dart... Love to do sports :-)

Updated on December 05, 2022

Comments

  • T R
    T R over 1 year

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