Flutter

Flutter 计算App应用缓存及清除应用缓存

2020-03-19  本文已影响0人  StevenHu_Sir

整体思路

1.计算App应用缓存

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

  // 加载缓存
  Future<String> loadCache() async {
    Directory tempDir = await getTemporaryDirectory();
    double value = await _getTotalSizeOfFilesInDir(tempDir);
    /*tempDir.list(followLinks: false,recursive: true).listen((file){
          //打印每个缓存文件的路径
        print(file.path);
      });*/
    print('临时目录大小: ' + value.toString());
    return  _renderSize(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;
  }
  // 递归方式删除目录
  Future<Null> _delDir(FileSystemEntity file) async {
    if (file is Directory) {
      final List<FileSystemEntity> children = file.listSync();
      for (final FileSystemEntity child in children) {
        await _delDir(child);
      }
    }
    await file.delete();
  }
  // 计算大小
  _renderSize(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);
    if (size ==  '0.00'){
      return '0M';
    }
    // print('size:${size == 0}\n ==SIZE${size}');
    return size + unitArr[index];
  }

2.清除App缓存

/// 清理缓存
///
void _clearCache() async {
    Directory tempDir = await getTemporaryDirectory();
    //删除缓存目录
    await _delDir(tempDir);
    await loadCache();
    Toast.show('清除缓存成功');
}

3.渲染文字(使用)

 String _cacheSizeStr = '0';
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getCount();
  }
  void getCount() async{
    _cacheSizeStr  = await loadCache();
    print('===cacheSize大小:${_cacheSizeStr}');
    setState(() {

    });
  }

补充

1.清理和获取图片缓存

 /// 清理内存:
  //clear all of image  in memory
  void clearMemoryImageCache() {
    PaintingBinding.instance.imageCache.clear();
  }

  // get ImageCache
  void getMemoryImageCache() {
    PaintingBinding.instance.imageCache;
  }

注意

Future<String> 要想获取其中的内容,前面必须+await 才可以,否则会报错

上一篇 下一篇

猜你喜欢

热点阅读