save method

Future<void> save()

Saves the settings back to the settings file. To avoid a corrupted file in the event of a crash we first copy the existing settings file to a .bak file. If the save fails you may need to manually rename the .bak file.

Implementation

Future<void> save() async {
  final tmp = createTempFilename();

  await withOpenLineFile(tmp, (file) async {
    file.write('# SettingsYaml settings file');

    for (final pair in valueMap.entries) {
      if (pair.value is String) {
        /// quote the string to ensure it doesn't get interpreted
        /// as a num/bool etc and import.
        file.append('${pair.key}: "${pair.value}"');
      } else {
        file.append('${pair.key}: ${pair.value}');
      }
    }
  });

  /// Do a safe save.
  final back = '$filePath.bak';
  if (exists(back)) {
    delete(back);
  }
  if (exists(filePath)) {
    move(filePath, back);
  }
  move(tmp, filePath);
  if (exists(back)) {
    delete(back);
  }
}