Fix large cache size (#437)

* Add custom cache manager

* Fix

* Add cleanup

* Remove prints for debugging

* Remove unnecessary code

* Change nr of max cache objects
This commit is contained in:
Artiu 2025-04-07 04:58:37 +02:00 • committed by GitHub
parent eb3d09749f
commit f72614afa7
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
8 changed files with 244 additions and 187 deletions

44
lib/cache_manager.dart Normal file
View file

@ -0,0 +1,44 @@
import 'dart:io';
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'package:path_provider/path_provider.dart';
class CustomCacheManager {
static const key = 'libCachedImageData';
static final _repo = CacheObjectProvider(databaseName: key);
static final instance = CacheManager(
Config(
key,
stalePeriod: const Duration(days: 30),
maxNrOfCacheObjects: 10000,
repo: _repo,
),
);
static Future<void> removeOrphanedCacheFiles() async {
final tempDir = await getTemporaryDirectory();
final cacheDir = Directory('${tempDir.path}/$key');
if (!await cacheDir.exists()) {
return;
}
final allFiles = cacheDir.listSync(recursive: true).toList();
await _repo.open();
final cachedObjects = await _repo.getAllObjects();
final dbFiles = cachedObjects.map((e) => e.relativePath).toSet();
final orphanedFiles = allFiles.where((file) {
final relativePath = file.path.split('$key/').last;
return !dbFiles.contains(relativePath);
}).toList();
final deletions = orphanedFiles.map((file) => file.delete()).toList();
try {
await Future.wait(deletions);
// ignore: empty_catches
} catch (e) {}
}
}