json_cache.dart 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import 'dart:convert';
  2. import 'dart:io';
  3. import 'package:path_provider/path_provider.dart';
  4. abstract class JsonCache<T> {
  5. final String cacheFileName;
  6. JsonCache(this.cacheFileName);
  7. Future<File> _getCacheFile() async {
  8. final basePath = await getTemporaryDirectory();
  9. final basePathName = basePath.path;
  10. final file = File("$basePathName/$cacheFileName.bin");
  11. return file;
  12. }
  13. Future<bool> isValid() async {
  14. final file = await _getCacheFile();
  15. return await file.exists();
  16. }
  17. Future<void> invalidate() async {
  18. final file = await _getCacheFile();
  19. await file.delete();
  20. }
  21. Future<void> putRawData(dynamic data) async {
  22. final jsonString = json.encode(data);
  23. final file = await _getCacheFile();
  24. if (!await file.exists()) {
  25. await file.create();
  26. }
  27. await file.writeAsString(jsonString);
  28. }
  29. dynamic readRawData() async {
  30. final file = await _getCacheFile();
  31. final data = await file.readAsString();
  32. return json.decode(data);
  33. }
  34. void put(T data);
  35. Future<T> get();
  36. }