如何使Image.network在变量为空时显示不同的图像?

huangapple go评论49阅读模式
英文:

How do I get an Image.network to show a different image if a variable is null

问题

How do I show a different image if a _readProfile is null

I tried the picture above and it is erroring out

英文:

如何使Image.network在变量为空时显示不同的图像?
How do I show a different image if a _readProfile is null

I tried the picture above and it is erroring out

答案1

得分: 1

你可以使用 ?? - 如果为空操作符来在一行中完成:

Image.network(_readProfile?.image.toString() ?? 'Your link')
英文:

You can do it in one line by using ?? - if null operator

Image.network(_readProfile?.image.toString() ?? 'Your link')

答案2

得分: 0

你需要创建一个返回 Widget 的方法。

并且它将按如下方式工作:

Widget getImage() {
  if (_readProfile != null) {
    return Image.network('YOUR LINK');
  } else {
    return Image.asset('URL FROM ASSET FOLDER');
  }
}

然后,你只需调用这个方法:

Container(
  child: getImage(),
)

它会为你工作。

英文:

You need to create a method with return Widget.

And it will work as below

  Widget getImage() {
    if (_readProfile != null) {
      return Image.network('YOUR LINK');
    } else {
      return Image.asset('URL FROM ASSET FOLDER');
    }
  }

Then you just need to call this method

Container(
  child: getImage(),
)

It will work for you.

答案3

得分: 0

以下是翻译好的部分:

在你的应用中添加一个默认图像
例如:

const String _defaultImage =
    "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQK_rZWRT_RXyeRBWmGHQB52XAdSfSFFbIMHyCqWZ0&s";
现在你可以在Image.network中使用它

Image.network(
        a ?? _defaultImage,           
      ),
并且如果错误来自服务器,你可以添加一个默认图标

Image.network(
        a ?? _defaultImage,
        errorBuilder: (context, error, stackTrace) => const Icon(Icons.person)),
      ),
英文:

add a default image in you app
for exemple

const String _defaultImage =
    "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQK_rZWRT_RXyeRBWmGHQB52XAdSfSFFbIMHyCqWZ0&s";

now you can use it in Image.network

Image.network(
        a ?? _defaultImage,           
      ),

and you can add a default icon if the error will come from the server

 Image.network(
        a ?? _defaultImage,
        errorBuilder: (context, error, stackTrace) => const Icon(Icons.person)),
      ),

答案4

得分: 0

你可以使用 errorBuilder 属性:

Image.network(
      "图片网址",
      errorBuilder: (context, error, _){
        return Image.asset("图片网址");
      },
    );
英文:

You can use errorBuilder property:

Image.network(
      "Image URL",
      errorBuilder: (context, error,_){
        return Image.asset("Image URL");
      },
    );

</details>



huangapple
  • 本文由 发表于 2023年2月17日 23:40:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/75486378.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定