mirror of https://github.com/AMT-Cheif/drift.git
Fix enum converter not handling null properly
This commit is contained in:
parent
d3f757235f
commit
c40c588f7a
|
@ -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;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -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));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
Loading…
Reference in New Issue