Browse Source

feat(neon): Reset SelectOption if value is not in values

Signed-off-by: jld3103 <jld3103yt@gmail.com>
pull/1079/head
jld3103 1 year ago
parent
commit
195d11eeda
No known key found for this signature in database
GPG Key ID: 9062417B9E8EB7B3
  1. 22
      packages/neon/neon/lib/src/settings/models/option.dart
  2. 15
      packages/neon/neon/test/option_test.dart

22
packages/neon/neon/lib/src/settings/models/option.dart

@ -71,6 +71,7 @@ sealed class Option<T> extends ChangeNotifier implements ValueListenable<T>, Dis
/// listeners.
@override
T get value => _value;
@mustCallSuper
set value(final T newValue) {
if (_value == newValue) {
@ -88,6 +89,7 @@ sealed class Option<T> extends ChangeNotifier implements ValueListenable<T>, Dis
/// value as evaluated by the equality operator ==, this class notifies its
/// listeners.
bool get enabled => _enabled;
@mustCallSuper
set enabled(final bool newValue) {
if (_enabled == newValue) {
@ -108,7 +110,9 @@ sealed class Option<T> extends ChangeNotifier implements ValueListenable<T>, Dis
final value = deserialize(data);
if (value != null) {
this.value = value;
// Do not trigger the validation to avoid resetting when the values haven't been loaded yet.
_value = value;
notifyListeners();
}
}
@ -203,10 +207,14 @@ class SelectOption<T> extends Option<T> {
@override
set value(final T value) {
super.value = value;
if (value != null) {
unawaited(storage.setString(key.value, serialize()!));
if (_values.keys.contains(value)) {
super.value = value;
if (value != null) {
unawaited(storage.setString(key.value, serialize()!));
}
} else {
debugPrint('"$value" is not in "${_values.keys.join('", "')}", ignoring');
}
}
@ -224,6 +232,10 @@ class SelectOption<T> extends Option<T> {
return;
}
_values = newValues;
if (!_values.keys.contains(_value)) {
debugPrint('"$value" is not in "${_values.keys.join('", "')}", resetting "${key.value}"');
reset();
}
notifyListeners();
}

15
packages/neon/neon/test/option_test.dart

@ -147,6 +147,21 @@ void main() {
expect(option.values, newValues, reason: 'Should keep the values.');
});
test('Invalid values', () {
expect(option.values, equals(valuesLabel));
option
..value = SelectValues.second
..values = {
SelectValues.first: (final _) => 'first',
SelectValues.third: (final _) => 'third',
};
expect(option.value, SelectValues.first, reason: 'Invalid value.');
option.value = SelectValues.second;
expect(option.value, SelectValues.first, reason: 'Invalid value.');
});
test('Reset', () {
final callback = MockCallbackFunction();
option

Loading…
Cancel
Save