2022-10-19 22:03:54 +02:00
|
|
|
import 'dart:convert';
|
|
|
|
import 'dart:io';
|
|
|
|
|
2023-01-18 17:59:23 +02:00
|
|
|
import 'package:flutter/foundation.dart';
|
2022-10-19 22:03:54 +02:00
|
|
|
import 'package:path_provider/path_provider.dart';
|
|
|
|
|
|
|
|
abstract class JsonCache<T> {
|
|
|
|
final String cacheFileName;
|
|
|
|
|
|
|
|
JsonCache(this.cacheFileName);
|
|
|
|
|
|
|
|
Future<File> _getCacheFile() async {
|
|
|
|
final basePath = await getTemporaryDirectory();
|
|
|
|
final basePathName = basePath.path;
|
|
|
|
|
|
|
|
final file = File("$basePathName/$cacheFileName.bin");
|
|
|
|
|
|
|
|
return file;
|
|
|
|
}
|
|
|
|
|
|
|
|
Future<bool> isValid() async {
|
|
|
|
final file = await _getCacheFile();
|
|
|
|
return await file.exists();
|
|
|
|
}
|
|
|
|
|
|
|
|
Future<void> invalidate() async {
|
2022-11-28 18:01:09 +02:00
|
|
|
try {
|
|
|
|
final file = await _getCacheFile();
|
|
|
|
await file.delete();
|
|
|
|
} on FileSystemException {
|
|
|
|
// file is already deleted
|
|
|
|
}
|
2022-10-19 22:03:54 +02:00
|
|
|
}
|
|
|
|
|
2023-01-18 17:59:23 +02:00
|
|
|
static Future<String> _computeEncodeJson(dynamic toEncode) async {
|
|
|
|
return json.encode(toEncode);
|
|
|
|
}
|
|
|
|
|
2022-10-19 22:03:54 +02:00
|
|
|
Future<void> putRawData(dynamic data) async {
|
2023-01-18 17:59:23 +02:00
|
|
|
final jsonString = await compute(_computeEncodeJson, data);
|
|
|
|
|
2022-10-19 22:03:54 +02:00
|
|
|
final file = await _getCacheFile();
|
|
|
|
|
|
|
|
if (!await file.exists()) {
|
|
|
|
await file.create();
|
|
|
|
}
|
|
|
|
|
|
|
|
await file.writeAsString(jsonString);
|
|
|
|
}
|
|
|
|
|
2023-01-18 17:59:23 +02:00
|
|
|
static Future<dynamic> _computeDecodeJson(String jsonString) async {
|
|
|
|
return json.decode(jsonString);
|
|
|
|
}
|
|
|
|
|
|
|
|
Future<dynamic> readRawData() async {
|
2022-10-19 22:03:54 +02:00
|
|
|
final file = await _getCacheFile();
|
|
|
|
final data = await file.readAsString();
|
2023-01-18 17:59:23 +02:00
|
|
|
|
|
|
|
return await compute(_computeDecodeJson, data);
|
2022-10-19 22:03:54 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
void put(T data);
|
|
|
|
Future<T> get();
|
2022-11-28 18:01:09 +02:00
|
|
|
}
|