Error: The argument type ‘DateTime?’ can’t be assigned to the parameter type ‘DateTime’.
@override
Widget build(BuildContext context) {
final formatter = LastUpdatedDateFormatter(
lastUpdated: _endpointsData != null ? _endpointsData.values[Endpoint.cases]!.date : null,
);
2
Answers
Solved: I removed nulls in my statement then casted as DateTime.
lastUpdated: _endpointsData.values[Endpoint.cases]?.date as DateTime,
?
next to the type declaration means that a variable is nullable, meaning it can accept anull
valueFor example:
String? a = null
is valid, whileString bar = null
is not a valid statement.In your expression
lastUpdated: _endpointsData != null ? _endpointsData.values[Endpoint.cases]!.date : null
, there is a possibility for thelastUpdated
parameter to receive anull
value, which it does not expect or accept. It needs to receive aDateTime
object. Consider using a default value, for example –DateTime.now()
instead of null:For more info, refer to Dart docs at https://dart.dev/null-safety