简体   繁体   中英

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

Below Code i have created for local caching 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);
      }

for first time, File can be Created. But For Second time.. Once File is created, and API fetches latest response with updated data, Cache file not get overwritten.

It would be great, if anyone can help on this..

Thanks in Advance.

i suppose that in your case happening something similar, to my situation:

For flutter Image class i found that, it use ImageCache for caching images, so when you rewrite Image and save it in filesystem, image will look the same until you restart app or invalidate cache.

Code that i wrote for cache invalidation for image:

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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