美文网首页Flutter
Flutter Cache获取和清除

Flutter Cache获取和清除

作者: wuyukobe | 来源:发表于2020-05-21 14:53 被阅读0次
一、简介

Flutter 获取应用缓存需要借助于path_provider插件。 path_provider 是一个用于查找文件系统上常用位置的Flutter插件。用来获取 Android 和 iOS 的缓存文件夹,然后再根据文件循环计算出缓存文件的大小。

以下是官方解释:

A Flutter plugin for finding commonly used locations on the filesystem. Supports iOS and Android.

目前可用最高版本为1.6.8。版本来源参考:path_provider 1.6.8

二、方法介绍

path_provider中获取文件夹的方法:

1、getTemporaryDirectory() ///< 在iOS上,对应NSTemporaryDirectory();在Android上,对应getCacheDir

2、getApplicationDocumentsDirectory() ///< 在iOS上,对应NSDocumentsDirectory;在Android上,对应AppData目录。

3、getExternalStorageDirectory() ///< 在iOS上,抛出异常,在Android上,对应getExternalStorageDirectory

以下是源码注释:


/// Path to the temporary directory on the device.
///
/// Files in this directory may be cleared at any time. This does *not* return
/// a new temporary directory. Instead, the caller is responsible for creating
/// (and cleaning up) files or directories within this directory. This
/// directory is scoped to the calling application.
///
/// On iOS, this uses the `NSCachesDirectory` API.
///
/// On Android, this uses the `getCacheDir` API on the context.
Future<Directory> getTemporaryDirectory() async {
  // TODO(amirh): remove this on when the invokeMethod update makes it to stable Flutter.
  // https://github.com/flutter/flutter/issues/26431
  // ignore: strong_mode_implicit_dynamic_method
  final String path = await _channel.invokeMethod('getTemporaryDirectory');
  if (path == null) {
    return null;
  }
  return Directory(path);
}

/// Path to a directory where the application may place files that are private
/// to the application and will only be cleared when the application itself
/// is deleted.
///
/// On iOS, this uses the `NSDocumentsDirectory` API.
///
/// On Android, this returns the AppData directory.
Future<Directory> getApplicationDocumentsDirectory() async {
  final String path =
      // TODO(amirh): remove this on when the invokeMethod update makes it to stable Flutter.
      // https://github.com/flutter/flutter/issues/26431
      // ignore: strong_mode_implicit_dynamic_method
      await _channel.invokeMethod('getApplicationDocumentsDirectory');
  if (path == null) {
    return null;
  }
  return Directory(path);
}

/// Path to a directory where the application may access top level storage.
/// The current operating system should be determined before issuing this
/// function call, as this functionality is only available on Android.
///
/// On iOS, this function throws an UnsupportedError as it is not possible
/// to access outside the app's sandbox.
///
/// On Android this returns getExternalStorageDirectory.
Future<Directory> getExternalStorageDirectory() async {
  if (Platform.isIOS)
    throw UnsupportedError("Functionality not available on iOS");
  // TODO(amirh): remove this on when the invokeMethod update makes it to stable Flutter.
  // https://github.com/flutter/flutter/issues/26431
  // ignore: strong_mode_implicit_dynamic_method
  final String path = await _channel.invokeMethod('getStorageDirectory');
  if (path == null) {
    return null;
  }
  return Directory(path);
}
三、使用介绍

1、pubspec.yaml文件下添加依赖库:path_provider: ^1.6.8。并执行flutter packages get操作,若出现问题,可适当降低依赖版本。

# 添加文件依赖
path_provider: ^1.6.8

2、导入头文件

import 'package:path_provider/path_provider.dart';
import 'dart:io';

3、缓存的获取(以getApplicationDocumentsDirectory()方法为例)

  /// 获取缓存
  Future<double> loadApplicationCache() async {
    /// 获取文件夹
    Directory directory = await getApplicationDocumentsDirectory();
    /// 获取缓存大小
    double value = await getTotalSizeOfFilesInDir(directory);
    return value;
  }

  /// 循环计算文件的大小(递归)
  Future<double> getTotalSizeOfFilesInDir(final FileSystemEntity file) async {
    if (file is File) {
      int length = await file.length();
      return double.parse(length.toString());
    }
    if (file is Directory) {
      final List<FileSystemEntity> children = file.listSync();
      double total = 0;
      if (children != null)
        for (final FileSystemEntity child in children)
          total += await getTotalSizeOfFilesInDir(child);
      return total;
    }
    return 0;
  }
  
  /// 缓存大小格式转换
  String formatSize(double value) {
    if (null == value) {
      return '0';
    }
    List<String> unitArr = List()
      ..add('B')
      ..add('K')
      ..add('M')
      ..add('G');
    int index = 0;
    while (value > 1024) {
      index++;
      value = value / 1024;
    }
    String size = value.toStringAsFixed(2);
    return size + unitArr[index];
  }

4、缓存的清除

  /// 删除缓存
  void clearApplicationCache() async {
    Directory directory = await getApplicationDocumentsDirectory();
    //删除缓存目录
    await deleteDirectory(directory);
  }

  /// 递归方式删除目录
  Future<Null> deleteDirectory(FileSystemEntity file) async {
    if (file is Directory) {
      final List<FileSystemEntity> children = file.listSync();
      for (final FileSystemEntity child in children) {
        await deleteDirectory(child);
      }
    }
    await file.delete();
  }

5、测试代码

获取缓存:

onPressed: () async {
                double value = await cacheManage.loadApplicationCache();
                String str = cacheManage.formatSize(value);
                print('获取app缓存: ' + str);
              },

删除缓存:

onPressed: (){
                cacheManage.clearApplicationCache();
                print('删除缓存');
              },

打印结果:

I/flutter (10920): 获取app缓存: 12.00B
I/flutter (10920): 删除缓存
I/flutter (10920): 获取app缓存: 0.00B

以上介绍了以getApplicationDocumentsDirectory()方法来获取主目录下的缓存,将该方法替换成另外两种方法同样适用。

相关文章

网友评论

    本文标题:Flutter Cache获取和清除

    本文链接:https://www.haomeiwen.com/subject/mkvzohtx.html