How to declare a variable depending on if statement in Dart? In Kotlin it would look like this:
val max = if (a > b) {
a
} else {
b
}
Is it even possible in Dart?
@pskink's answer in the comment is correct but it didn't show how you would be able to do it in this scenario. Here is how you can do it in your scenario:
final max= a > b ? a : b;
The final keyword in Dart is the same as the val keyword in Kotlin. You will not be able to change the value of the variable. You could also use the var keyword in Dart which is the same as Kotlin's var keyword. You will be able to change the value of the variable after declaring it. You might be confused with the one-liner code since there isn't any if or else statements inside it. The code above is called a ternary operator.
Here is an explanation for it:
(condition/expresssion) ? val1(if true execute this) : val2(if false execute this)
if(){max=a}else{max=b} to execute more than one statement.val c = if (a > b) { a } else if (a == b) { 0 } else { b }For more than one statement, we can use a method by declaring its type as int.
void main() {
print(declareVariable());
}
int a = 10;
int b = 30;
int declareVariable() {
if(b < a){
return 1;
}
else if(b > a) {
return 2;
}
else {
return 0;
}
}
Edited :
We can declare more then one condition in single line in the same way.
var singleLine = b < a ? 1 : b > a ? 2 : 0;
This will print out the same answer as method.
var something = bool_expression ? val1 : val2- check dart.dev/guides/language/language-tour for more info