2

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

Galih indra
  • 333
  • 1
  • 4
  • 13

2 Answers2

5

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.

Oswin Noetzelmann
  • 9,166
  • 1
  • 33
  • 46
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

Tacratis
  • 1,035
  • 1
  • 6
  • 16