Skip to content

Fix FormatException cause by empty json file #487

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ class JsonCacheInfoRepository extends CacheInfoRepository
Future<void> _readFile(File file) async {
_cacheObjects.clear();
_jsonCache.clear();
if (await file.exists()) {
if (await file.exists() && await file.length() > 0) {
try {
final jsonString = await file.readAsString();
final json = jsonDecode(jsonString) as List<dynamic>;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import 'dart:io';

import 'package:collection/collection.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_cache_manager/src/storage/cache_info_repositories/json_cache_info_repository.dart';
import 'package:flutter_cache_manager/src/storage/cache_object.dart';
import 'package:flutter_test/flutter_test.dart';
Expand Down Expand Up @@ -41,6 +42,25 @@ void main() {
await repository.open();
});

test('Open repository should not report error when file is empty',
() async {
var 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;
});

test('An open repository can be closed', () async {
var repository = await JsonRepoHelpers.createRepository();
var isClosed = await repository.close();
Expand Down