Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check null in ternary operation

Tags:

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

like image 474
Israel Nascimento Avatar asked Apr 11 '18 12:04

Israel Nascimento


People also ask

Does ternary operator check for undefined?

Set a Variable's Value if it's Undefined using Ternary # Copied! A ternary operator is very similar to an if/else statement. If the condition ( myVar === undefined ) returns true , the value to the left of the colon is returned, otherwise the value to the right is returned.

Is null ternary operator PHP?

The null coalescing operator is a useful feature of PHP that can be used as an alternative to the ternary operator and the isset() function. It is better than the ternary operator because it is faster and can check the values of multiple variables via chaining, as shown in the second example.

How do you read a ternary operator?

The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.

What is use of NULL coalesce operator?

Uses of Null Coalescing Operator: It is used to replace the ternary operator in conjunction with the PHP isset() function. It can be used to write shorter expressions. It reduces the complexity of the program. It does not throw any error even if the first operand does not exist.


1 Answers

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) {    ... } 
like image 154
Rémi Rousselet Avatar answered Nov 11 '22 06:11

Rémi Rousselet