-
Hi, I am migrating to null safety. I have a JsonSerializer ( I have this error How to serialize in nullable type ?
import 'package:moor/moor.dart';
import '../../types/date.dart';
class DateConverter extends TypeConverter<Date, int> {
const DateConverter();
@override
Date? mapToDart(int? fromDb) {
if (fromDb == null) {
return null;
}
return Date.fromDateTime(DateTime.fromMillisecondsSinceEpoch(fromDb));
}
@override
int? mapToSql(Date? value) {
return value?.millisecondsSinceEpoch;
}
static int today() => DateTime.now().toUtc().millisecondsSinceEpoch;
} class JsonSerializer extends ValueSerializer {
const JsonSerializer();
@override
T fromJson<T>(dynamic json) {
if (T == DateTime) {
return DateTime.parse(json as String) as T;
}
if (T == Date) {
return Date.fromJson(json as String) as T;
}
return json as T;
}
@override
dynamic toJson<T>(T value) {
if (value is DateTime) {
return value.toUtc().toIso8601String();
}
if (value is Date) {
return value.toJson();
}
return value;
}
} |
Beta Was this translation helpful? Give feedback.
Answered by
simolus3
May 27, 2021
Replies: 1 comment 1 reply
-
You could do something like this: final listOfT = <T>[];
if (listOfT is List<DateTime?>) {
return DateTime.parse(json as String) as T;
}
if (listOfT is List<Date?>) {
return Date.fromJson(json as String) as T;
}
|
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
lsaudon
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You could do something like this:
listOfT
will be aList<Date?>
ifT
is assignable toDate?
which is probably what you want.