flutterdarttry-catchflutter-assetimage

Dart try/catch - catch block does not work


In my flutter app I want to load assets depending on condition: is my code running as imported package or as an app I'm currently develop.

The problem is that this try/catch block always fails in try section:

AssetImage _getBackgroundImage() {
    try {
      return AssetImage(
        'lib/assets/images/menu_background.png',
        package: 'my_package',
      );
    } catch (e) {
      return AssetImage('lib/assets/images/menu_background.png');
    }
  }

run output:

======== Exception caught by image resource service ================================================
The following assertion was thrown resolving an image codec:
Unable to load asset: packages/my_package/lib/assets/images/menu_background.png

When the exception was thrown, this was the stack: 
#0      PlatformAssetBundle.load (package:flutter/src/services/asset_bundle.dart:227:7)
<asynchronous suspension>
#1      AssetBundleImageProvider._loadAsync (package:flutter/src/painting/image_provider.dart:667:14)
<asynchronous suspension>
Image provider: AssetImage(bundle: null, name: "packages/my_package/lib/assets/images/menu_background.png")
Image key: AssetBundleImageKey(bundle: PlatformAssetBundle#e01ff(), name: "packages/my_package/lib/assets/images/menu_background.png", scale: 1.0)
====================================================================================================


Solution

  • AssetImage is loading the image async later on, as you can see in the stack trace. Therefore the creation of the AssetImage object won't throw an exception until the Flutter is drawing the image. This results in your catch clause never getting called.

    To solve the issue you probably best of checking beforehand if the image exists. Here is a question with answers on stackoverflow on how to do it.