Thanapol Thong-art
Thanapol Thong-art

Reputation: 43

How to use short if in flutter?

How to use short if in flutter

this code can use:

1 + 1 == 2 ? print('check true') : print('check false');
Ans. print('check true')

but I want to do this:

1 + 1 == 2 ?? print('check true');

Why code can't print check true?

Upvotes: 2

Views: 15892

Answers (3)

You can do this, I think is shorter and easy understand: if (1+1 == 2) print('check true');

Upvotes: 1

prahack
prahack

Reputation: 1619

Simply

1 + 1 == 2 ? print('check true') : print('check false');

is equals to

if(1+1 == 2) {
    print('check true');
else {
    print('check false');
}

and

1 + 1 == 2 ?? print('check true');

is equals to

if((1+1 == 2) == null ) {
    print('check true');
}

Upvotes: 9

w461
w461

Reputation: 2698

The short form always require an else statement. And as said in the comments, ?? provides a default value if an object is null. With widgets, you could for example always write a == b ? c() : Container() because you cannot see Container() without a size

Upvotes: 1

Related Questions