clearDiskCachedImages static method

Future<bool> clearDiskCachedImages({
  1. Duration? duration,
  2. String? cacheTag,
})

Clear the disk cache directory then return if it succeed.

Implementation

static Future<bool> clearDiskCachedImages(
    {Duration? duration, String? cacheTag}) async {
  try {
    final Directory cacheImagesDirectory = Directory(getJoin(
        (await getAppTemporaryDirectory()).path, cacheImageFolderName));
    if (cacheImagesDirectory.existsSync()) {
      final DateTime now = DateTime.now();
      await for (final FileSystemEntity file in cacheImagesDirectory.list()) {
        final FileStat fs = file.statSync();

        void deleteSync() {
          var flag = false;
          if (cacheTag != null) {
            if (getBasenameWithoutExtension(file.path).contains(cacheTag)) {
              flag = true;
              file.deleteSync(recursive: true);
            }
          } else {
            flag = true;
            file.deleteSync(recursive: true);
          }
          logDebug(
              "delete: ${duration?.inSeconds}s - ${fs.changed} - ${getBasenameWithoutExtension(file.path)} - $flag");
        }

        if (duration == null) {
          deleteSync();
        } else {
          if (now.subtract(duration).isAfter(fs.changed)) {
            deleteSync();
          }
        }
      }
    }
  } catch (_) {
    return false;
  }
  return true;
}