1. 程式人生 > >[Flutter] Image.File 載入影象時檔案內容變化顯示不變解決

[Flutter] Image.File 載入影象時檔案內容變化顯示不變解決

在Flutter中,我們可以用下面的程式碼從檔案中載入影象:

Image.file(File(_fileName));

這個時候,當_fileName這個檔名稱和路徑不變,檔案內容變化時,Flutter並不會更新顯示。問題產生的原因是Flutter自動使用了快取。

那麼怎麼辦呢?

我檢視到,Image.file 實際上會將 image 設定為 FileImage 這個 ImageProvider。FileImage 的程式碼中,在進行 operator 時,只判斷了檔案路徑和縮放比例。正是因為如此,我們檔案路徑不變,縮放比例不變時,Flutter會認為我們還是用的原圖,並不會重新進行載入。

於是,我想到了辦法是擴充套件一個FileImage,將這個 operator 的方式改一下。

class FileImageEx extends FileImage {
  int fileSize;
  FileImageEx(File file, { double scale = 1.0 })
      : assert(file != null),
        assert(scale != null),
        super(file, scale: scale) {
    fileSize = file.lengthSync();
  }

  @override
  bool operator 
==(dynamic other) { if (other.runtimeType != runtimeType) return false; final FileImageEx typedOther = other; return file?.path == typedOther.file?.path && scale == typedOther.scale && fileSize == typedOther.fileSize; } }

接下來,直接使用下面的程式碼來載入影象:

Image(image: FileImageEx(File(_fileName)));

經測試,問題得到解決。

如果您有更好的方式,歡迎留言。