3

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.

2
  • Hi Pradeep Bansal, have you checked this pub.dev/packages/flutter_cache_manager, if it might help you Commented Aug 2, 2021 at 16:12
  • Isn't there any way with path provider ? Commented Aug 2, 2021 at 16:43

1 Answer 1

0

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
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.