what does question mark mean in these codes?

5,340

Solution 1

It is the ternary operator (or short-if). For example the following is equivalent:

if (COND) {
   X = A;
} else {
   X = B;
}

X = COND ? A : B; // if COND condition is met, execute A, otherwise execute B

See this article.

In your example if the variable alreadySaved is true the Icons.favorite is used as well as Colors.red. If alreadySaved is false, then Icons.favorite_border is used together with null for the color.

Solution 2

It is an immediate if, so it basically means if then assign first value, else (marked by ':') assign second value.

simple example:

x = True? 1 : 2

will assign 1

x = False? 1: 2

will assign 2

Also see this question: Java Equivalent to iif function

Share:
5,340
Galih indra
Author by

Galih indra

Updated on December 08, 2022

Comments

  • Galih indra
    Galih indra over 1 year

    these source code is from flutter tutorial

    Widget _buildRow(WordPair pair) { final bool alreadySaved = _saved.contains(pair); return new ListTile( title: new Text( pair.asPascalCase, style: _biggerFont, ), trailing: new Icon( // Add the lines from here... alreadySaved ? Icons.favorite : Icons.favorite_border, color: alreadySaved ? Colors.red : null, ), // ... to here. ); }

    what does this part mean? trailing: new Icon( // Add the lines from here... alreadySaved ? Icons.favorite : Icons.favorite_border, color: alreadySaved ? Colors.red : null, ), // ... to here. can someone make another form of this code but with the same logic? I don't understand this part