Setting<T> constructor
Setting<T> ({
- required Settings settings,
- required String key,
- required T decode(),
- required RawSettingValue encode(
- T
A single setting that exposes a type T
to the consuming application.
The _key
is a function that returns the key
for the setting. The _decode
function is used to convert the raw value
from the underlying storage to the type T
. The _encode
function is
used to convert the value of type T
to a raw value that can be stored
in the underlying storage.
Implementation
Setting({
required Settings settings,
required String key,
required T Function(RawSettingValue) decode,
required RawSettingValue Function(T) encode,
}) : _decode = decode,
_encode = encode,
_key = key,
_settings = settings {
final $key = _key;
value = _settings._group.writable(
_decode(_toRawValue(_settings._storage.get($key))),
name: '${$key}_value',
);
// Any time `value` changes, persist the new value to the underlying storage.
_settings._group.effect(
() async {
final $value = value.value;
final $key = _key;
if (_settings._storage.get($key) != $value) {
final encoded = _encode($value);
await switch (encoded) {
StringSettingValue() =>
_settings._storage.setString($key, encoded.value),
IntSettingValue() => _settings._storage.setInt($key, encoded.value),
DoubleSettingValue() =>
_settings._storage.setDouble($key, encoded.value),
BoolSettingValue() =>
_settings._storage.setBool($key, encoded.value),
StringListSettingValue() =>
_settings._storage.setStringList($key, encoded.value),
NullSettingValue() => _settings._storage.remove($key),
};
}
},
name: '${$key}_effect',
);
}