saveDataToDisc method

Future<String?> saveDataToDisc(
  1. Object? data,
  2. DataType dataType, {
  3. String? takeThisName,
  4. String? path,
  5. bool recursive = false,
})

Writes data to disk.

  • If path is provided, the data is written to that absolute path and the file name is derived from it.
  • Otherwise, the file is created inside filesPath using takeThisName as its name, or the current timestamp when takeThisName is null.
  • dataType drives how data is serialised: DataType.text treats it as a String, DataType.base64 decodes it and stores the decoded bytes, DataType.bytes stores it as a Uint8List.
  • When recursive is true, any missing parent directory is created; otherwise a FileSystemException is thrown if the parent directory does not exist.

Returns the file name actually used, or null when data is null / empty.

Implementation

Future<String?> saveDataToDisc(
  Object? data,
  DataType dataType, {
  String? takeThisName,
  String? path,
  bool recursive = false,
}) async {
  if (data == null) return null;
  if (data is String && data.isEmpty) return null;
  if (data is List && data.isEmpty) return null;

  String fileName;
  if (path != null) {
    fileName = path.split(pathJoin).last;
  } else {
    fileName = takeThisName ?? DateTime.now().toIso8601String();
  }

  if (Platform.isWindows) fileName = fileName.replaceAll(':', '');

  final String resolved = validatePath(path) ??
      '${await filesPath}$pathJoin$fileName';
  final File file = File(resolved);
  file.createSync(recursive: recursive);

  switch (dataType) {
    case DataType.text:
      file.writeAsStringSync(data as String);
      break;
    case DataType.base64:
      file.writeAsBytesSync(base64Decode(data as String));
      break;
    case DataType.bytes:
      file.writeAsBytesSync(data as Uint8List);
      break;
  }
  return fileName;
}