launchDate2 is also a DateTime? type. Why the heck it could be passed to a function that requires a DateTime argument?

Viewed 17

We couldn't pass a DateTime? value to a function that requires a DateTime argument. The code below results in an error.

class Spacecraft {
  String name;
  DateTime? launchDate;
  
  // Read-only non-final property
  int? get launchYear => launchDate?.year;
  
  // Constructor, with syntactic sugar for assignment to members.
  Spacecraft(this.name, this.launchDate) {
    // Initialization code go here.
  }
  
  // Named constructor that forwards to the default one.
  Spacecraft.unlaunched(String name) : this(name, null);
  
  // Method
  void describe() {
    print('Spacecraft: $name');
  
    if (launchDate != null) {
      int years = DateTime.now().difference(launchDate).inDays ~/ 365;
      print('Launched: $launchYear ($years years ago)');
    } else {
      print('Unlaunched');
    }
  }
}

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

However, this worked:

class Spacecraft {
  String name;
  DateTime? launchDate;
  
  // Read-only non-final property
  int? get launchYear => launchDate?.year;
  
  // Constructor, with syntactic sugar for assignment to members.
  Spacecraft(this.name, this.launchDate) {
    // Initialization code go here.
  }
  
  // Named constructor that forwards to the default one.
  Spacecraft.unlaunched(String name) : this(name, null);
  
  // Method
  void describe() {
    print('Spacecraft: $name');
  
    // Type promotion doesn't work on getters
    var launchDate2 = launchDate;
    if (launchDate2 != null) {
      int years = DateTime.now().difference(launchDate2).inDays ~/ 365;
      print('Launched: $launchYear ($years years ago)');
    } else {
      print('Unlaunched');
    }
  }
}

And heck, launchDate2 is also a DateTime? type. Why the heck it could be passed to a function that requires a DateTime argument?

1 Answers
Related