0

我正在尝试使用此代码加载图像

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

但是如果图像没有建立,我想用默认图像替换它,我试试这个代码

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;
}

我已经在 pubspec.yaml 中添加了所有图像依赖项我只想用默认值替换图像,如果在文件夹中找不到它

这是错误:

════════ 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)
════════════════════════════════════════════════════════════════════════════════════════════════════
4

1 回答 1

0

您应该只为小部件string内的图像资产返回 a ,CircleAvatar如下面的代码:

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

该方法现在返回一个string

String getImage(String image) {
    String img;
    try {
      img = 'images/${widget.categoria}/$image.png';
    } catch (e) {
      img = 'images/non_disp_big.png';
    }
    return img;
  }
于 2020-05-01T15:33:55.267 回答