Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting default values that are non constant in Dart

Tags:

dart

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.

like image 396
90intuition Avatar asked Jul 11 '18 08:07

90intuition


2 Answers

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);
  
  
}
like image 117
MarkDionee B Avatar answered Sep 28 '22 10:09

MarkDionee B


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.

like image 36
Günter Zöchbauer Avatar answered Sep 28 '22 10:09

Günter Zöchbauer