3

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?

2
  • 1
    stackoverflow.com/questions/58910273/… Commented Jan 12, 2021 at 13:07
  • The ?? is called null aware and checks if 1+1==2 is null. If the expression on the left of ?? evaluates to null then the print statement is executed. Commented Jan 12, 2021 at 13:12

3 Answers 3

10

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');
}
Sign up to request clarification or add additional context in comments.

1 Comment

just tried 1 + 1 == 2 ?? print('check true');. This does not work. ?? provides a default value in case the expression to the left is null
1

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.