How do I set default values for parameters that are non constant?
I came up with this:
class Todo {
final DateTime createdAt;
final DateTime updatedAt;
Todo({DateTime createdAt, DateTime updatedAt})
: createdAt = createdAt != null ? null : DateTime.now(),
updatedAt = updatedAt != null ? null : DateTime.now();
}
I was wondering if it could be done shorter, for example I tried this:
class Todo {
final DateTime createdAt;
final DateTime updatedAt;
Todo({DateTime createdAt, DateTime updatedAt})
: createdAt ??= DateTime.now(),
updatedAt ??= DateTime.now();
}
But that did not work.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With