【问题标题】:Removing image from cache when using Image.network使用 Image.network 时从缓存中删除图像
【发布时间】:2020-11-15 13:27:26
【问题描述】:

我正在使用 Image.Network 显示基于 URL 的图像:

ClipOval(
                                  child: Image.network(
                                    'http://myurl${userId}.png',
                                    width: 100,
                                    height: 100,
                                    fit: BoxFit.cover,
                                    key: profileImageKey,
                                  ),
                                ),

我正在尝试让用户上传新的个人资料图片,但是,我保留了相同的文件名(用户 ID + .png)。用户上传图片后,上面的显示不会显示新图片。

我尝试使用以下方法重建小部件:

setState(() {
                                            //generateKey();
                                            profileImageKey = ValueKey(new Random().nextInt(100));
                                            userId = userId;
                                          });

我还尝试使用以下方法从缓存中删除 url:

PaintingBinding.instance.imageCache.evict('http://myurl${userId}.png');

但是,这些方法都不起作用。有没有办法更新 Image.Network 以下载和使用上传的新图像?

谢谢

【问题讨论】:

标签: flutter


【解决方案1】:

基于@pskink 的评论https://stackoverflow.com/a/60916852/2252830

这个问题的解决方案是对 Image 使用 evict 方法。所以我将我的代码重构到下面:

Image profileImage;

...

profileImage = Image.network(
                                    'http://myurl${userId}.png',
                                    width: 100,
                                    height: 100,
                                    fit: BoxFit.cover,
                                    key: profileImageKey,
                                  );

...

ClipOval(
                                  child: profileImage,
                                ),

...

profileImage.image.evict();
                                              
                                              setState(() {
                                                //generateKey();
                                                profileImageKey = ValueKey(new Random().nextInt(100));
                                                userId = userId;
                                              });

【讨论】:

  • new Random().nextInt(100) 不是一个好主意 - 你需要一个真正唯一的密钥 - random 不提供这个
  • 有没有我可以做的替代品?
  • @pskink 不幸的是,evict 对我不起作用。我认为确实如此,但是在第一次第二次上传之后以及之后的任何内容都不起作用。我什至物理删除了我的服务器(firebase 存储)上的文件,它仍然显示我的个人资料图像。假设这仍然在缓存中。
猜你喜欢
  • 2013-01-14
  • 1970-01-01
  • 1970-01-01
  • 2014-10-20
  • 2022-12-09
  • 2016-07-13
  • 2013-07-14
  • 2020-04-25
  • 2013-07-09
相关资源
最近更新 更多