Дисковый кэш с обобщениями Я программист, работающий на JavaScript и PHP, и разрабатываю приложение для Flutter, и мне трудно реализовать кэш во внутренней памяти телефона.
Я хотел бы понятьи знать, возможно ли создать класс универсального типа с сериализацией для JSON, чтобы его можно было сохранить в файле.Я сделал реализацию Cache в памяти, и она работает нормально, плюс реализация Cache на диске у меня возникли трудности.
Код для кэш-памяти
class MemCache<T> extends Cache<T> {
Duration cacheValidDuration = Duration(minutes: 30);
DateTime lastFetchTime = DateTime.fromMillisecondsSinceEpoch(0);
RList<T> allRecords = RList<T>();
//is updade cache
bool isShouldRefresh() {
return (null == allRecords ||
allRecords.isEmpty ||
null == lastFetchTime ||
lastFetchTime.isBefore(DateTime.now().subtract(cacheValidDuration)));
}
@override
Future<RList<T>> getAll() {
return Future.value(allRecords);
}
@override
Future<void> putAll(RList<T> objects) {
allRecords.addAll(objects);
lastFetchTime = DateTime.now();
}
@override
Future<void> putAllAsync(Future<RList<T>> objects) async {
allRecords = await objects;
}
}
Код для дискового кэша Как вызвать метод сериализации из универсального
class DiskCache<T> extends Cache<T> {
Duration cacheValidDuration = Duration(minutes: 30);
DateTime lastFetchTime = DateTime.fromMillisecondsSinceEpoch(0);
RList<T> allRecords = RList<T>();
//is update the cache
bool isShouldRefresh() {
return (null == allRecords ||
allRecords.isEmpty ||
null == lastFetchTime ||
lastFetchTime.isBefore(DateTime.now().subtract(cacheValidDuration)));
}
@override
Future<RList<T>> getAll() async {
await _readFromDisk();
return Future.value(allRecords);
}
@override
Future<void> putAll(RList<T> objects) async {
allRecords.addAll(objects);
lastFetchTime = DateTime.now();
await _writeToDisk();
}
@override
Future<void> putAllAsync(Future<RList<T>> objects) async {
allRecords = await objects;
lastFetchTime = DateTime.now();
await _writeToDisk();
}
//parth
Future<String> get _localPath async {
final directory = await getApplicationDocumentsDirectory();
return directory.path;
}
//file pointer
Future<File> get _localFile async {
final path = await _localPath;
return File('$path/allRecords.json');
}
//write to file
Future<File> _writeToDisk() async {
try {
File recordedFile;
if (allRecords != null) {
var map = allRecords.map((c) {
var item = c as ISerialization;
return item.toJson();
}).toList();
var jsonString = jsonEncode(map);
final file = await _localFile;
// Write the file
recordedFile = await file.writeAsString(jsonString);
}
return recordedFile;
} catch (e) {
print("writeToDisk: " + e.toString());
return null;
}
}
// ************************** issues on this part ******************
Future<RList<T>> _readFromDisk() async {
try {
final file = await _localFile;
// Read the file
String contents = await file.readAsString();
var parsedJson = jsonDecode(contents);
if (allRecords == null) {
allRecords = RList<T>();
}
allRecords.clear();
for (var item in parsedJson) {
// ************************** issues on this part ******************
print(T.fromMap(item));
allRecords.add(T.fromMap(item));
}
return allRecords;
} catch (e) {
print("readFromDisk: " + e.toString());
return null;
}
}
}
Ошибка: метод 'fromMap' не определен для класса 'Type'.- «Тип» от «дротик: ядро».Попробуйте исправить имя с именем существующего метода или определить метод с именем «fromMap».allRecords.add (T.fromMap (пункт));^^^^^^^