1

In my Flutter app, I return asset (product image) name by:

class Product {
    // ...
    final int id;
    // ...
    String get assetName => '$id-0.jpg';
}

And later, I use the asset name like:

// ...
image: AssetImage(product.assetName),
// ...

Now, the problem is some of the images are *.jpg and some are *.png like:

Screenshot

Is there a way to tell the Flutter image loader to try to load '$id-0.jpg' and if the file doesn't exist, then try to load '$id-0.png'? Perhaps I can do that with regular expressions, but I cannot figure out how.

Megidd
  • 7,089
  • 6
  • 65
  • 142

1 Answers1

1

You can determine if an asset exists with rootBundle.load and a try-catch block. rootBundle.load will throw an exception if the asset is not found.

ByteData image;
try{
  image = await rootBundle.load(assetNameHere.jpg);
}
catch(e) {
  image = await rootBundle.load(assetNameHere.png);
}

I don't know the exception that this will throw on the asset not existing, so I can't tell you which error to catch on, but you can figure that out and modify your code to only do the png code on that exception type instead of everything.

With this method, since you're already forced to load the image into memory, you can store the ByteData and use MemoryImage instead of AssetImage.

Christopher Moore
  • 15,626
  • 10
  • 42
  • 52
  • Also, [such conversion](https://stackoverflow.com/a/56573060/3405291) is needed. – Megidd Oct 23 '20 at 13:06
  • Moreover, due to using `await` keyword, I had to note [this](https://stackoverflow.com/a/53801912/3405291) and [that](https://stackoverflow.com/a/53364252/3405291) ... – Megidd Oct 23 '20 at 13:08