The argument type 'DateTime?' can't be assigned to the parameter type 'DateTime'

6,361

This removed the error-

final dateString = dateFormatter.format(item!.date as DateTime);
Share:
6,361
abhimanyu
Author by

abhimanyu

Updated on January 02, 2023

Comments

  • abhimanyu
    abhimanyu over 1 year

    In Book : Flutter Apprentice First Edition, I had below code:

    import 'package:flutter/painting.dart';
    // 1
    enum Importance { low, medium, high }
    class GroceryItem {
    // 2
    final String id;
    // 3
    final String name;
    final Importance importance;
    final Color color;
    final int quantity;
    final DateTime date;
    final bool isComplete;
    ...
    

    And the build method as

    Widget buildDate() {
        final dateFormatter = DateFormat('MMMM dd h:mm a');
        final dateString = dateFormatter.format(item!.date);
        return Text(
          dateString,
          style: TextStyle(decoration: textDecoration),
        );
      }
    

    I have the below error:

    The argument type 'DateTime?' can't be assigned to the parameter type 'DateTime'.

  • abhimanyu
    abhimanyu over 2 years
    But I am wondering whether it is right?
  • G H Prakash
    G H Prakash over 2 years
    Yes, this is right. its a type of hack.
  • ישו אוהב אותך
    ישו אוהב אותך over 2 years
    Don't use ! if the variable have a probability of becoming null. Either initialized the variable with default value or using if null else.