Check null in ternary operation

2019-04-07 23:49发布

问题:

I wanna put a default value on a textfield if _contact is not null. To do this

new TextField(
    decoration: new InputDecoration(labelText: "Email"), 
    maxLines: 1,
    controller: new TextEditingController(text: (_contact != null) ? _contact.email: ""))

Is there a better way to do that? E.g: Javascript would be something like: text: _contact ? _contact.email : ""

回答1:

Dart comes with ?. and ?? operator for null check.

You can do the following :

var result = _contact?.email ?? ""

You can also do

if (t?.creationDate?.millisecond != null) {
   ...
}

Which in JS is equal to :

if (t && t.creationDate && t.creationDate.millisecond) {
   ...
}


标签: dart flutter