Fix enum converter not handling null properly

This commit is contained in:
Simon Binder 2021-07-12 14:59:08 +02:00
parent d3f757235f
commit c40c588f7a
No known key found for this signature in database
GPG Key ID: 7891917E4147B8C0
2 changed files with 28 additions and 5 deletions

View File

@ -22,7 +22,7 @@ abstract class TypeConverter<D, S> {
/// Implementation for an enum to int converter that uses the index of the enum /// Implementation for an enum to int converter that uses the index of the enum
/// as the value stored in the database. /// as the value stored in the database.
class EnumIndexConverter<T> extends TypeConverter<T, int> { class EnumIndexConverter<T> extends NullAwareTypeConverter<T, int> {
/// All values of the enum. /// All values of the enum.
final List<T> values; final List<T> values;
@ -30,13 +30,15 @@ class EnumIndexConverter<T> extends TypeConverter<T, int> {
const EnumIndexConverter(this.values); const EnumIndexConverter(this.values);
@override @override
T? mapToDart(int? fromDb) { T requireMapToDart(int fromDb) {
return fromDb == null ? null : values[fromDb]; return values[fromDb];
} }
@override @override
int? mapToSql(T? value) { int requireMapToSql(T value) {
return (value as dynamic)?.index as int; // In Dart 2.14: Cast to Enum instead of dynamic. Also add Enum as an upper
// bound for T.
return (value as dynamic).index as int;
} }
} }

View File

@ -0,0 +1,21 @@
import 'package:moor/moor.dart';
import 'package:test/test.dart';
enum _MyEnum { one, two, three }
void main() {
const converter = EnumIndexConverter(_MyEnum.values);
const values = {_MyEnum.one: 0, _MyEnum.two: 1, _MyEnum.three: 2, null: null};
group('encodes', () {
values.forEach((key, value) {
test('$key as $value', () => expect(converter.mapToSql(key), value));
});
});
group('decodes', () {
values.forEach((key, value) {
test('$key as $value', () => expect(converter.mapToDart(value), key));
});
});
}