cache.dart 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import 'dart:typed_data';
  2. import 'package:dio/dio.dart' as dio;
  3. import 'package:flutter/material.dart';
  4. class VidImageWebCache {
  5. VidImageWebCache._();
  6. static VidImageWebCache? _instance;
  7. /// 缓存空间大小
  8. // ignore: prefer_final_fields
  9. static int _cacheSize = 20 * 1024 * 1024;
  10. static VidImageWebCache get ins {
  11. _instance ??= VidImageWebCache._();
  12. return _instance!;
  13. }
  14. /// 设置缓存大小
  15. ///
  16. /// Remark: 设为0表示禁用缓存
  17. static void setCacheSize(int size) {
  18. if (size == 0) {
  19. _cacheSize = 0;
  20. _instance?._clearCache();
  21. } else {
  22. _cacheSize = size * 1024 * 1024;
  23. }
  24. }
  25. final _cacheMap = <String, Uint8List>{};
  26. /// 已使用缓存空间大小,单位 byte
  27. int get usedSize =>
  28. _cacheMap.values.map((e) => e.length).reduce((v, e) => v + e);
  29. /// 加载缓存数据
  30. Future<Uint8List?> load(String url) async {
  31. //
  32. _saveCache(url, Uint8List.fromList([]));
  33. // http
  34. return null;
  35. }
  36. /// 移除缓存数据
  37. Future<void> remove(String url) async {
  38. if (_cacheMap.containsKey(url)) {
  39. _cacheMap.remove(url);
  40. }
  41. }
  42. void _clearCache() => _cacheMap.clear();
  43. void _saveCache(String url, Uint8List data) {
  44. if (_cacheSize == 0) return;
  45. _cacheMap[url] = data;
  46. }
  47. }