safeWriteFileAsync function

Future<void> safeWriteFileAsync(
  1. String targetPath,
  2. String content
)

Writes content to a file asynchronously, ensuring the parent directory exists.

Parameters:

  • targetPath: The String path of the file to write to.
  • content: The String content to write to the file.

Implementation

Future<void> safeWriteFileAsync(String targetPath, String content) async {
  final file = File(targetPath);

  try {
    await file.parent.create(recursive: true);

    await file.writeAsString(content, mode: FileMode.write, flush: true);
  } catch (e) {
    print('Error writing to file $targetPath: $e');
    rethrow;
  }
}