当Flutter中imageUrl动态更改时,CachedNetworkImage不显示占位符 [英] CachedNetworkImage does not show the placeholder when imageUrl dynamically change in Flutter
问题描述
我希望CachedNetworkImage在加载新图像时更改imageUrl属性时显示占位符,但它显示的是先前imageUrl中的前一个图像。
I want the CachedNetworkImage to display placeholder when I change the imageUrl property while it loads the new image, but instead, it is showing the previous image from previous imageUrl.
例如,如果我有这样的设置,其中有一个CachedNetworkImage和一个按钮。按下按钮后,状态将更新,并且CachedNetworkImage的imageUrl属性将更新。发生这种情况时,我希望CachedNetworkImage在从新图像Url加载新图像时显示占位符。如何实现我想要的?
For example, if I have a setup like this where I have a CachedNetworkImage and a button. When the button is pressed, the state is updated and the imageUrl property of CachedNetworkImage is updated. When this happens, I want the CachedNetworkImage to display placeholder while it loads the new image from the new image Url. How can I achieve what I want?
class SampleState extends State<SamplePage> {
String imageUrl = "https://example.com/someImage.png";
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
CachedNetworkImage(
imageUrl: imageUrl,
placeholder: Center(child: CircularProgressIndicator()
),
RaisedButton(
child: Text("Change image"),
onPressed: () {
setState(() {
imageUrl = "https://example.com/anotherImage.png";
});
},
),
],
);
}
}
推荐答案
您可以通过更改 key
的值来强制完全重建窗口小部件,例如,可以创建 ValueKey
字符串-具有相同url的两个键是相等的。
You can force a widget to be completely rebuilt by changing the value of the key
. For example, you can create a ValueKey
from the url String - two keys with the same url are equal.
class SampleState extends State<SamplePage> {
String imageUrl = "https://example.com/someImage.png";
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
CachedNetworkImage(
key: new ValueKey<String>(imageUrl),
imageUrl: imageUrl,
placeholder: Center(child: CircularProgressIndicator()
),
RaisedButton(
child: Text("Change image"),
onPressed: () {
setState(() {
imageUrl = "https://example.com/anotherImage.png";
});
},
),
],
);
}
}
这篇关于当Flutter中imageUrl动态更改时,CachedNetworkImage不显示占位符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!