In Dart we might want to set a variable to some fixed value, but which variable we set may depend on some bool expression. For example
String value = 'Hello World!';
bool sendToFirst = false;
String first = '';
String second = '';
if (sendToFirst){
first = value;
else {
second = value;
}
This block would do what you want, but is there a more concise way of doing this? Something like
(sendToFirst ? first : second) = value;
But of course this does not work.
CodePudding user response:
There is a way to simplify if statements: Ternary expressions. Following your example you have to code:
sendToFirst ? first = value : second = value
In the end you are just replacing the keywords with syntactic sugar, where the ?
replaces the "if bool is true"-part, followed by a condition that should be executed (the body of the condition) and the colon :
for the else-part, again, followed by a body.
FYI: You can mark value final, if you are not planning to re-asign a new value to it.