Different behavior ternary operator - if/else with spread operator (...)
Your use of the ternary operator doesn't work because each of the "then" and "else" operands (and therefore the result of the ternary operator itself) must evaluate to an expression, and the spread operator (...
) doesn't produce an expression. The spread operator (and collection-if
and collection-for
) instead evaluates to one or more collection elements. (I highly recommend reading Bob Nystrom's article that discusses the design of these language features.)
Your use of the ternary operator would work if you moved the spread operator out:
...(isLogged ? loggedRows(context) : [loginRow(context)]),
although that is more awkward since it creates an extra List
if isLogged
is false. Using collection-if
instead would be much more appropriate for this usage.
Carlos
Updated on January 01, 2023Comments
-
Carlos about 1 year
Why the following code works fine with if/else and not with ternary operator?
ListView( children: [ // Commented code not working // isLogged ? ...loggedRows(context) : loginRow(context), // Working code if (isLogged) ...loggedRows(context) else loginRow(context), ListTile(...), ListTile(...), ])
loggedRows and loginRow methods:
ListTile loginRow(BuildContext context) { return ListTile(...) } List<ListTile> loggedRows(BuildContext context) { return [ListTile(...), ListTile(...)]; }
I try to show different ListTiles depending on if the user is logged in or not, and it works perfectly using if/else but when I try to do the same with ternary operator I get error.
I tried several parenthesis combinations, but none of them worked for me.
Using the simplest mode, as in commented code, I get 3 errors on Dart Analysis:
- Expected to find ']'.
- Expected to find '.'.
- Expected an identifier.
Shouldn't behave the same ternary operator and if/else?
Why do I get these errors?
Does anyone know which should be the right syntax to use ternary operator?
-
Yeasin Sheikh over 2 yearsIt is the same as this thread
-
Carlos over 2 yearsYes, you're right. Sorry, I didn't find that threat. Anyway... shouldn't it work with ternary operator? If not, why not?
-
pedro pimont over 2 yearsthose two are not the same. ternary operators are expressions and if else are statements
-
jamesdlin over 2 years@pedropimont Not quite,
if
-else
in this case is collection-if
, which is more akin to an expression instead of to a statement.