From c9cb8171a5fd8a8ebdb99b9ff2ca98630ef03239 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 800f4ba1..76141c22 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 @@ -137,7 +137,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 0e6e1dba..1ada291a 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));