【问题标题】:Load deafult image if Image.asset not found the image如果 Image.asset 未找到图像,则加载默认图像
【发布时间】:2020-08-16 02:29:39
【问题描述】:

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

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

【问题讨论】:

  • 你的代码中是否到达了 catch 子句?

标签: flutter dart flutter-image uiimageasset


【解决方案1】:

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

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

【讨论】:

  • 如何检查我的资产文件夹中是否存在此资产?
  • 看看this
  • 我需要返回字符串而不是 Future 的东西,现在我已经解决了在没有资产的情况下删除数据
  • 有问题您说过当资产图像不可用时加载默认图像,您可以通过io.File(path).exists() 在 if 语句中执行此操作,就好像它返回 true 那么文件存在现在您可以设置图像到该文件,如果它现在返回 false,您可以使用默认图像。
  • 我用 'images/${widget.categoria}/$image.png' 代替了“路径”,但总是返回 false
猜你喜欢
  • 2023-02-05
  • 2019-10-23
  • 1970-01-01
  • 2015-06-03
  • 2016-05-20
  • 1970-01-01
  • 2017-08-14
  • 2015-08-20
  • 2022-01-09
相关资源
最近更新 更多