buildPathInCache static method

Future<String> buildPathInCache({
  1. String subPath = '',
  2. String fileName = '',
})

构建Caches下的路径

示例代码:

// 构建目录路径
String path1 = await PPath.buildPathInCache(subPath: 'dir1'); // 返回 Caches/dir1

// 构建文件路径
String path2 = await PPath.buildPathInCache(fileName: 'file.txt'); // 返回 Caches/file.txt

// 构建带子目录的文件路径
String path3 = await PPath.buildPathInCache(subPath: 'dir1', fileName: 'file.txt'); // 返回 Caches/dir1/file.txt
String path4 = await PPath.buildPathInCache(subPath: 'dir1/dir2', fileName: 'file.txt'); // 返回 Caches/dir1/dir2/file.txt

Implementation

static Future<String> buildPathInCache({
  String subPath = '',
  String fileName = '',
}) async {
  var fullPath = (await PPath.appCacheDir()).path;
  // 如果 subPath 不为空,则拼接 subPath 并确保目录存在
  if (subPath.isNotEmpty) {
    fullPath = dart_path.join(fullPath, subPath);
    final parentDir = Directory(fullPath);
    if (!await parentDir.exists()) {
      await parentDir.create(recursive: true);
    }
  }
  // 如果 fileName 不为空,则拼接 fileName 到路径
  if (fileName.isNotEmpty) {
    fullPath = dart_path.join(fullPath, fileName);
  }
  return fullPath;
}