MonkeyBrain
MonkeyBrain

Reputation: 113

Flutter check if Asset image exists

Is it possible to conditionally load an asset image, only if it exists? Therefore you could load a default image if it does not exist in the Assets bundle.

Upvotes: 2

Views: 3792

Answers (1)

Omatt
Omatt

Reputation: 10473

One way you can check if the asset image exists is by trying to display it. If it throws an Exception, display a different widget instead.

Future<Widget> getAssetImage(String path) async {
  try {
    await rootBundle.load(path);
    return Image.asset(path);
  } catch (_) {
    return SizedBox(); // Return this widget
  }
}

Otherwise, you can check the AssetManifest.json and cross-check the asset to be used with the list before trying to access it.

Upvotes: 2

Related Questions