Load deafult image if Image.asset not found the image

2.1k views Asked by At

I am trying to load an image with this code

CircleAvatar(
    child: Image(
    image: getImage(snapshot.value['img']),
    ),
),

but if the image is not founded I want to replace it with a default image and I try this code

AssetImage getImage(String image) {
    AssetImage img;
    try {
        img = AssetImage('images/${widget.categoria}/$image.png');
    } catch (e) {
        img = AssetImage('images/non_disp_big.png');
    }
    return img;
}

I allready add all images dependencies in pubspec.yaml I just wanna replace the image with a default if not found it in the folder

This is the error:

════════ Exception caught by image resource service ════════════════════════════════════════════════
The following assertion was thrown resolving an image codec:
Unable to load asset: images/produzioni-tipiche/biplano.png

When the exception was thrown, this was the stack: 
#0      PlatformAssetBundle.load (package:flutter/src/services/asset_bundle.dart:221:7)
<asynchronous suspension>
#1      AssetBundleImageProvider._loadAsync (package:flutter/src/painting/image_provider.dart:484:44)
#2      AssetBundleImageProvider.load (package:flutter/src/painting/image_provider.dart:469:14)
#3      ImageProvider.resolve.<anonymous closure>.<anonymous closure>.<anonymous closure> (package:flutter/src/painting/image_provider.dart:327:17)
...
Image provider: AssetImage(bundle: null, name: "images/produzioni-tipiche/biplano.png")
Image key: AssetBundleImageKey(bundle: PlatformAssetBundle#15081(), name: "images/produzioni-tipiche/biplano.png", scale: 1.0)
════════════════════════════════════════════════════════════════════════════════════════════════════
2

There are 2 answers

5
hewa jalal On

you should just return a string for the image asset inside your CircleAvatar widget like the code below:

CircleAvatar(
            child: Image(
          image: AssetImage(getImage(snapshot.value['img'])),
        ))

the method returns a string now:

String getImage(String image) {
    String img;
    try {
      img = 'images/${widget.categoria}/$image.png';
    } catch (e) {
      img = 'images/non_disp_big.png';
    }
    return img;
  }
0
BYISHIMO Audace On

I know this is an old question, but the best way is user errorBuilder function that Image.asset provides and load for alternative widget.

 CircleAvatar(
      child: Image.asset(getImage(snapshot.value['img']),
      errorBuilder: ((context, error, stackTrace) => const Image.asset('images/non_disp_big.png')),
    )),