From 12b96ae50574a9fa8d68809cc694e22c3e0369c2 Mon Sep 17 00:00:00 2001 From: "a.amir" <> Date: Wed, 10 Sep 2025 15:21:12 +0200 Subject: [PATCH] fix: check a file has content before proccess --- .../json_cache_info_repository.dart | 3 ++- .../json_file_repository_test.dart | 20 +++++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/flutter_cache_manager/lib/src/storage/cache_info_repositories/json_cache_info_repository.dart b/flutter_cache_manager/lib/src/storage/cache_info_repositories/json_cache_info_repository.dart index e8ee293f..1cfdc5b0 100644 --- a/flutter_cache_manager/lib/src/storage/cache_info_repositories/json_cache_info_repository.dart +++ b/flutter_cache_manager/lib/src/storage/cache_info_repositories/json_cache_info_repository.dart @@ -135,7 +135,8 @@ class JsonCacheInfoRepository extends CacheInfoRepository Future _readFile(File file) async { _cacheObjects.clear(); _jsonCache.clear(); - if (await file.exists()) { + final hasContent = await file.length() > 0; + if (await file.exists() && hasContent) { try { final jsonString = await file.readAsString(); final json = jsonDecode(jsonString) as List; diff --git a/flutter_cache_manager/test/repositories/json_file_repository_test.dart b/flutter_cache_manager/test/repositories/json_file_repository_test.dart index 941738f5..e920a431 100644 --- a/flutter_cache_manager/test/repositories/json_file_repository_test.dart +++ b/flutter_cache_manager/test/repositories/json_file_repository_test.dart @@ -57,6 +57,26 @@ void main() { }); }); + test('Open repository should not report error when file is empty', + () async { + final originalOnError = FlutterError.onError; + FlutterError.onError = (FlutterErrorDetails details) { + throw details.exception; + }; + + final tempFile = File('${Directory.systemTemp.path}/test_empty.json'); + await tempFile.create(); + expect(await tempFile.length(), 0); + + final repository = JsonCacheInfoRepository.withFile(tempFile); + await repository.open(); + + expect(await repository.getAllObjects(), isEmpty); + + await tempFile.delete(); + FlutterError.onError = originalOnError; + }); + group('Exist and delete', () { test('New repository does not exist', () async { var repository = JsonCacheInfoRepository.withFile(File(path));