Dart try/catch - catch block does not work

543 views Asked by At

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)
====================================================================================================

2

There are 2 answers

0
hfxbse On BEST ANSWER

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.

1
Anushka Pubudu On

Try & Catch blocks are used to catch some errors in software runtime environment. As your question you make some codes in catch block because try is always failles. This is not a standard. Always try to make your code with coding standards.

Second thing is I saw in your code make assets folder inside your project folder not in lib file.