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?
Thanks!
CodePudding user response:
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.