繁体   English   中英

如何在使用路径提供程序时覆盖或更新 Flutter 中的缓存文件

[英]How to Overwrite or Update Cache files in Flutter while using Path Provider

下面的代码是我使用路径提供程序为本地缓存创建的

String fileName="pathString.json";
var dir=await getTemporaryDirectory();
File file=File(dir.path+"/"+fileName);

if(!file.existsSync()) {
        final http.Response response = await http.get(
            Uri.parse("https://*************.herokuapp.com/*********"));
        file.writeAsStringSync(
            response.body, flush: true, mode: FileMode.write);
        final data = file.readAsStringSync();
        responseData = json.decode(data);
      }else{
        final data = file.readAsStringSync();
        responseData = json.decode(data);
        final http.Response response = await http.get(
            Uri.parse("https://**************.herokuapp.com/*********"));
        file.writeAsStringSync(
            response.body, flush: true, mode: FileMode.write);
      }

第一次,可以创建文件。 但是第二次.. 一旦文件被创建,并且 API 获取带有更新数据的最新响应,缓存文件就不会被覆盖。

如果有人可以帮助解决这个问题,那就太好了..

提前致谢。

我想在你的情况下发生了与我的情况类似的事情:

对于 flutter Image class 我发现,它使用ImageCache缓存图像,因此当您重写图像并将其保存在文件系统中时,图像看起来是一样的,直到您重新启动应用程序或使缓存无效。

我为图像缓存失效编写的代码:

import 'dart:io';
import 'package:flutter/material.dart';

// imgBytes - raw image bytes here empty just for example
// location - path to image in fs
updateImage(Uint8List imgBytes) async {
  var file = File(location);
  await file.writeAsBytes(imgBytes, mode: FileMode.write); // rewrite file content

  var img = Image.file(file); // create Image class
  img.image.evict(); // invalidate cache key for this image
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM