diff --git a/moor/lib/src/runtime/types/custom_type.dart b/moor/lib/src/runtime/types/custom_type.dart index 643112f8..d446b177 100644 --- a/moor/lib/src/runtime/types/custom_type.dart +++ b/moor/lib/src/runtime/types/custom_type.dart @@ -22,7 +22,7 @@ abstract class TypeConverter { /// Implementation for an enum to int converter that uses the index of the enum /// as the value stored in the database. -class EnumIndexConverter extends TypeConverter { +class EnumIndexConverter extends NullAwareTypeConverter { /// All values of the enum. final List values; @@ -30,13 +30,15 @@ class EnumIndexConverter extends TypeConverter { const EnumIndexConverter(this.values); @override - T? mapToDart(int? fromDb) { - return fromDb == null ? null : values[fromDb]; + T requireMapToDart(int fromDb) { + return values[fromDb]; } @override - int? mapToSql(T? value) { - return (value as dynamic)?.index as int; + int requireMapToSql(T value) { + // 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; } } diff --git a/moor/test/types/enum_index_converter_test.dart b/moor/test/types/enum_index_converter_test.dart new file mode 100644 index 00000000..93d90d00 --- /dev/null +++ b/moor/test/types/enum_index_converter_test.dart @@ -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)); + }); + }); +}