flutter3d
Showcase Changelog 62 packages API reference

Settings, config and saves

since 0.7.0 Widgets and the rest

A player's choices and a player's progress are two different documents on purpose: wiping a corrupt save should not cost anybody their key bindings. GameSettings holds the first as a value: a volume per audio bus, typed settings under namespaced keys, and the player's action map, each change a copy. SaveFile holds the second as a level path and a snapshot, and SettingsPanel is the Flutter widget, made of SettingsSections, that lets a player change the first.

Note. SaveFile is thinner than it looks: underneath its own few lines it is entirely the real Storage and Snapshot, so this page calls those directly. SettingsPanel is described here rather than built.

Step 1: A setting of the game's own #

/// A setting of this game's own: typed, under its own namespace, with what it
/// is when the player has not chosen.
const SettingKey<bool> _subtitles = SettingKey<bool>(
  'showcase.subtitles',
  fallback: true,
);

Step 2: A save that is mostly real storage #

/// Where a run in progress is kept. Everything below the field names is the
/// real `Storage` and `Snapshot` this app already depends on.
final class _SaveFile {
  _SaveFile({required String appName}) : _storage = defaultStorage(appName);

  final Storage _storage;
  static const String _name = 'save.json';

  Future<({String level, Snapshot run})?> read() async {
    final text = await _storage.read(_name);
    if (text == null) return null;
    final json = jsonDecode(text) as Map<String, Object?>;
    return (
      level: json['level']! as String,
      run: Snapshot.fromJson(json['run']! as Map<String, Object?>),
    );
  }

  Future<void> write(String level, Snapshot run) => _storage.write(
    _name,
    jsonEncode(<String, Object?>{'level': level, 'run': run.toJson()}),
  );

  Future<void> clear() => _storage.remove(_name);
}

Step 3: Use both #

final config = const GameSettings()
    .withVolume(AudioBus.music, 0.6)
    .withValue(GameSettingKeys.cameraMotion, 0.0)
    .withValue(_subtitles, false);
final musicVolume = config.volumeOf(AudioBus.music);
final sfxVolume = config.volumeOf(AudioBus.sfx);
final cameraMotion = config.valueOf(GameSettingKeys.cameraMotion);
// The file, in the envelope, read back.
final read = GameSettings.fromJson(config.toJson());
assert(!read.valueOf(_subtitles), 'a setting of its own came back');

A bus nobody has set defaults to full volume, and a setting nobody chose reads as its key's fallback. The file is written in the format envelope, and a key this build does not know is kept for the next write. A save written, read back and cleared answers exactly what each of those should: the level and state it was given, then nothing at all.