Cache file

Plug-in: path_provider

Path_provider can mask the file differences between the installation and ios

Common methods:

GetTemporaryDirectory Gets the cache folder path

Await getApplicationDocumentsDirectory () to obtain the app path

* await * external.getexternalstoragedirectory () the sd card path

Practical application:

  bool hasCach; // Check whether there is a cache
  @override
  void initState() {
    super.initState();
    loadCache();
  }

// Get the cached reference
  Future<File> getCache() async {
    String searchHistory = (await getTemporaryDirectory()).path;// Get the system cache path
    File sh = File('$searchHistory/searchHistiry.json');// File reference to the cache file to be used in the cache folder
    bool _hascache = await sh.exists();// Check if there is a cache
    if(! _hascache) {await sh.create();// Create file without cache file
    }
    return sh;// Returns a file reference to the cache file
  }

/ / load huanc
  loadCache() async {
    File sh = await getCache();
    String _history = await sh.readAsString();// Reads the file from the cache file reference to the String String
    setState(() {
      history = jsonDecode(_history);// Use josn to convert to List or Map data structures
    });
  }

  // Saving the cache will save the cache action abstraction
  sageCache() async {
    File sh = await getCache();
    await sh.writeAsString(jsonEncode(history));// Write the file to cache
  }

  // Empty all
  deleteAll() async {
    setState(() {
      history = List(a); });await sageCache();
  }
Copy the code

Note: This cannot be used in widgets that use cached files

@override
void dispose() { 
  super.dispose();
}			
Copy the code

This will destroy the cache file when the component is destroyed

View and clear app cache files

 String cacheSize;
  @override
  void initState() {
    super.initState();
    init();
  }

  init() async {
    await loadCache();
  }
  /// load the cache
  Future<Null> loadCache() async {
    try {
      Directory tempDir = await getTemporaryDirectory();
      double value = await _getTotalSizeOfFilesInDir(tempDir);
      setState(() {
        cacheSize = _renderSize(value).toString();
      });
    } catch (err) {
      print(err); }}/// Calculate file size recursively
  Future<double> _getTotalSizeOfFilesInDir(final FileSystemEntity file) async {
    try {
      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;
    } catch (e) {
      print(e);
      return 0; }}// delete the directory recursively
  Future<Null> delDir(FileSystemEntity file) async {
    try {
      if (file is Directory) {
        final List<FileSystemEntity> children = file.listSync();
        for (final FileSystemEntity child in children) {
          awaitdelDir(child); }}await file.delete();
    } catch (e) {
      print(e); }}void _clearCache() async {
    alert(context, title: Text('Clearing out... '), backgroundColor: Colors.deepOrange);
    try {
      Directory tempDir = await getTemporaryDirectory();
      // Delete the cache directory
      await delDir(tempDir);
      await loadCache();
    } catch (e) {
      print(e);
    } finally{ Navigator.pop(context); }}/// Format the file size
  _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);
    return size + unitArr[index];
  }

Copy the code