saveDataToDisc method

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

Writes data.

  • If path is provided, the data is written to that absolute path and the file name is derived from it. When recursive is true, any missing parent directory is created; otherwise a FileSystemException is thrown if the parent directory does not exist.
  • Otherwise, the file is created inside filesPath (created if needed) using takeThisName as its name, or the current timestamp when takeThisName is null. A name that would leave filesPath (such as ../x) throws an ArgumentError.
  • 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.
  • The file is written all at once: a reader sees the old content or the new one, never half of it.
  • When the database is encrypted (DataAccess.useEncryptionKey), a file saved by name is encrypted (AES-256-GCM); a file written at an explicit path (an export, for instance) is written as is unless encrypt is true.

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,
  bool? encrypt,
}) 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 (pathJoin == r'\') fileName = fileName.replaceAll(':', '');

  final String? validated = validatePath(path);
  final List<int> bytes = await _seal(
    _bytesOf(data, dataType),
    encrypt ?? validated == null,
  );
  await _locked(
    _lockKey(fileName, validated),
    () => _store.write(
      bytes,
      fileName: validated == null ? fileName : null,
      path: validated,
      recursive: recursive,
    ),
  );
  if (validated == null) await _record(fileName, saved: true);
  return fileName;
}