import 'dart:io'; extension FileExt on File { Future safeCopy(String newPath) async { if (!await exists()) { await create(recursive: true); return; } final targetFile = File(newPath); if (!await targetFile.exists()) { await targetFile.create(recursive: true); } await copy(newPath); } Future safeWriteAsString(String str) async { if (!await exists()) { await create(recursive: true); } return await writeAsString(str); } Future safeWriteAsBytes(List bytes) async { if (!await exists()) { await create(recursive: true); } return await writeAsBytes(bytes); } } extension FileSystemEntityExt on FileSystemEntity { Future safeDelete({bool recursive = false}) async { if (!await exists()) { return; } await delete(recursive: recursive); } }