Setting default values that are non constant in Dart

Solution Sample:
If the Order Date was wasn't specified, use DateNow....
If the Order Date was specified, use it.

Test my code on:
https://dartpad.dev/

class Order  {
  final String id;
  final double amount;
  final List cartItems;
  final DateTime? dateTime;

  Order(
      {required this.id,
      required this.amount,
      required this.cartItems,
       dateTime
       })
      :this.dateTime = ( dateTime != null ? dateTime : DateTime.now() );
}


void main() {
  
  var order_use_default_date = Order(id:"1",amount:1000,cartItems:[1,2,3]);
  var order_use_param_date = Order(id:"1",amount:1000,cartItems:[1,2,3],dateTime:DateTime.now().subtract(Duration(days: 2)) );
  
  print(order_use_default_date.dateTime);
  print(order_use_param_date.dateTime);
  
  
}

This is a shorter version that can be used:

class Todo {
  final DateTime createdAt;
  final DateTime updatedAt;

  Todo({DateTime? createdAt, DateTime? updatedAt})
      : createdAt = createdAt ?? DateTime.now(),
        updatedAt = updatedAt ?? DateTime.now();
}

Your version didn't work because in

createdAt = createdAt ?? DateTime.now()

the first and the 2nd createdAt refer to 2 different variables.
The former is implicitly this.createdAt and the later is the parameter value.

Tags:

Dart