skip to Main Content

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


  1. Chosen as BEST ANSWER

    Solved: I removed nulls in my statement then casted as DateTime.

    lastUpdated: _endpointsData.values[Endpoint.cases]?.date as DateTime,


  2. ? next to the type declaration means that a variable is nullable, meaning it can accept a null value

    For example: String? a = null is valid, while String bar = null is not a valid statement.

    In your expression lastUpdated: _endpointsData != null ? _endpointsData.values[Endpoint.cases]!.date : null, there is a possibility for the lastUpdated parameter to receive a null value, which it does not expect or accept. It needs to receive a DateTime object. Consider using a default value, for example – DateTime.now() instead of null:

    @override
      Widget build(BuildContext context) {
        final formatter = LastUpdatedDateFormatter(
          lastUpdated: _endpointsData != null ? _endpointsData.values[Endpoint.cases]!.date : DateTime.now(),
        );
    

    For more info, refer to Dart docs at https://dart.dev/null-safety

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search