Israel Nascimento
Israel Nascimento

Reputation: 680

Check null in ternary operation

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 : ""

Upvotes: 30

Views: 56281

Answers (2)

Rahul Kumar Tiwari
Rahul Kumar Tiwari

Reputation: 139

Sometimes null is also converted into a string. So you can check in 2 ways examples(s)

widget.cprice != 'null' - with string    
widget.cprice != null  - with pure null value

Upvotes: 3

Rémi Rousselet
Rémi Rousselet

Reputation: 277747

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) {
   ...
}

Upvotes: 69

Related Questions