flutter 显示缓存大小,清理缓存功能

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

以下是官方解释:

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

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

方法介绍
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';

页面初始化时循环获得缓存大小

double cache = 0.0;
void initState() {
    getSize();
    super.initState();
  }

  getSize() async {
    final _tempDir = await getTemporaryDirectory();
    double _cache = await Utils.getTotalSizeOfFilesInDir(_tempDir);
    setState(() {
      cache = _cache;
    });
  }
ClickItem(
  title: '清除缓存',
  content: Utils.renderSize(cache),
  onTap: () async {
    print('清除');
    try {
      final _tempDir = await getTemporaryDirectory();
      EasyLoading.show(status: '清除中');
      await Utils.requestPermission(_tempDir);
      EasyLoading.dismiss();
      EasyLoading.showSuccess('清除成功');
      getSize();
    } catch (err) {
      EasyLoading.dismiss();
      EasyLoading.showError('清除失败');
    }
  },
 ),

Utils中的方法

import 'dart:io';
import 'dart:typed_data';
import 'dart:ui';
import 'package:permission_handler/permission_handler.dart';

static Future<Null> requestPermission(FileSystemEntity file) async {
    PermissionStatus status = await Permission.storage.status;
    await delDir(file);
  }

  static Future<Null> delDir(FileSystemEntity file) async {
    if (file is Directory && file.existsSync()) {
      print(file.path);
      final List<FileSystemEntity> children =
          file.listSync(recursive: true, followLinks: true);
      for (final FileSystemEntity child in children) {
        await delDir(child);
      }
    }
    try {
      if (file.existsSync()) {
        await file.delete(recursive: true);
      }
    } catch (err) {
      print(err);
    }
  }

  //循环获取缓存大小
  static Future getTotalSizeOfFilesInDir(final FileSystemEntity file) async {
    //  File

    if (file is File && file.existsSync()) {
      int length = await file.length();
      return double.parse(length.toString());
    }
    if (file is Directory && file.existsSync()) {
      List children = file.listSync();
      double total = 0;
      if (children.length > 0)
        for (final FileSystemEntity child in children)
          total += await getTotalSizeOfFilesInDir(child);
      return total;
    }
    return 0;
  }

  //格式化文件大小
  static String renderSize(value) {
    if (value == null) {
      return '0.0';
    }
    List<String> unitArr = []
      ..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];
  }
### Flutter 打包时的缓存数据处理方法 在开发 Flutter 应用程序的过程中,缓存数据是一个常见的需求。为了确保应用程序在打包发布时能够正确管理这些缓存数据,开发者可以采用多种策略和技术手段。 #### 使用 `shared_preferences` 进行缓存数据存储 `shared_preferences` 是一种轻量级的数据持久化插件,适用于保存简单的键值对数据。通过该插件,可以在应用启动或运行期间读取和写入缓存数据[^3]。以下是具体实现方式: - **写入数据** 下面展示了如何向设备上存储不同类型的数据: ```dart import 'package:shared_preferences/shared_preferences.dart'; Future<void> saveData() async { final SharedPreferences prefs = await SharedPreferences.getInstance(); // 写入整数型数据 await prefs.setInt('counter', 10); // 写入布尔型数据 await prefs.setBool('repeat', true); // 写入浮点型数据 await prefs.setDouble('decimal', 1.5); // 写入字符串型数据 await prefs.setString('action', 'Start'); // 写入字符串列表型数据 await prefs.setStringList('items', ['Earth', 'Moon', 'Sun']); } ``` - **读取数据** 同样可以通过 `SharedPreferences` 实例调用对应的 getter 方法来获取已存储的数据: ```dart Future<void> readData() async { final SharedPreferences prefs = await SharedPreferences.getInstance(); int counter = prefs.getInt('counter') ?? 0; bool repeat = prefs.getBool('repeat') ?? false; double decimal = prefs.getDouble('decimal') ?? 0.0; String action = prefs.getString('action') ?? ''; List<String>? items = prefs.getStringList('items'); print('Counter: $counter, Repeat: $repeat, Decimal: $decimal, Action: $action, Items: $items'); } ``` #### 减少打包体积的技术方案 当涉及到优化 Flutter 应用的打包大小时,除了关注代码本身的精简外,还需要注意依赖库的选择以及构建配置文件中的设置。例如,在 Podfile 中启用 thin 模式可以帮助减少 iOS 平台下的二进制文件尺寸[^1]: ```ruby flutter 'your_flutter_project', 'x.x.x', :thin => true ``` 此外,建议定期执行清理命令以移除不必要的临时文件和旧版本资源: ```bash flutter clean ``` 对于 Android 平台,则可通过调整 Gradle 构建脚本进一步压缩 APK 文件大小。比如开启 ProGuard 或 R8 工具来进行混淆与缩减未使用的类成员操作。 #### 验证环境状态的重要性 在正式部署前务必确认本地开发工具链处于健康可用的状态下才能有效避免潜在错误发生。这一步骤通常借助于官方提供的诊断功能完成——即运行如下指令验证当前工作区是否存在异常情况[^2]: ```bash flutter doctor ``` 如果一切正常则可继续后续流程;反之需按照提示修复对应问题后再尝试重新编译项目。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值