gpt4 book ai didi

flutter - dart中如何写多个条件?

转载 作者:行者123 更新时间:2023-12-02 18:01:36 26 4
gpt4 key购买 nike

我知道我们可以将属性中的条件编写为三元运算符,如下所示

onTap: textType == "birth"
? () {
FocusScope.of(context).requestFocus(FocusNode());
showPicker(context, birthController,ref);
}
: null,

但是当涉及到多个条件时,我该如何重写代码?如下所示的代码被视为语法错误。

onTap:
if (textType == "birth"){
//do something
}else if(textType == "place"){
//do something
}else{
return null
}

最佳答案

您必须使用嵌套三元运算符。这有点丑陋,但你就是这么做的。

示例:myVar ? “你好”:myVar2? “嘿”:“哟”

这会检查第一个条件 (myVar),如果失败,则检查第二个条件 (myVar2)。您还可以在此处进行实际检查,而不是仅检查 bool 值。例如:myVar == 14

或者,您可以从代码中调用一个函数,在其中使用 if/else if/else 等。这是我推荐的。

例如,从代码中调用 getProperGreeting(),这将引用:

String getProperGreeting() {
... <if else chain> ...

}

关于flutter - dart中如何写多个条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74229963/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com