如何像在 Kotlin 中一样根据 Dart 中的 if 语句声明变量?

Tho*_*mas 2 variables functional-programming dart kotlin flutter

如何根据Dart中的if语句声明变量?在 Kotlin 中,它看起来像这样:

   val max = if (a > b) {
        a
    } else {
        b
    }
Run Code Online (Sandbox Code Playgroud)

在 Dart 中甚至有可能吗?

Uni*_*Uni 5

@pskink 在评论中的回答是正确的,但它没有显示在这种情况下您将如何做到这一点。在您的场景中,您可以这样做:

final max= a > b ? a : b;
Run Code Online (Sandbox Code Playgroud)

final在达特关键字是相同val的科特林关键字。您将无法更改变量的值。您也可以var在 Dart 中使用与 Kotlin 的var关键字相同的关键字。声明变量后,您将能够更改它的值。您可能会对单行代码感到困惑,因为其中没有任何 if 或 else 语句。上面的代码称为ternary operator.
这是对它的解释:

(condition/expresssion) ? val1(if true execute this) : val2(if false execute this)
Run Code Online (Sandbox Code Playgroud)


Ana*_*nas 4

对于多个语句,我们可以通过将方法声明为 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;
  }
} 
Run Code Online (Sandbox Code Playgroud)

编辑:

我们可以用同样的方式在一行中声明多个条件。

var singleLine = b < a ? 1 : b > a ? 2 : 0;
Run Code Online (Sandbox Code Playgroud)

这将打印出与方法相同的答案。