如何在Flutter小部件中使用If语句

8

我是Flutter的新手,正在练习制作简单的应用程序。但是现在,我可以插入一行条件语句,但我想添加if语句,以便我可以添加更多语句。我该怎么做?这是我的代码,请看一下。当达到目标金额时,我想要添加更多颜色color: _moneyCounter > 1000 ? Colors.green : Colors.red,

Expanded(
              child: Center(
                child: Text(
                  '\USD $_moneyCounter',
                  style: TextStyle(
                    color: _moneyCounter > 1000 ? Colors.green : Colors.red,
                    fontSize: 40.0,
                  ),
                ),
              ),
            ),
3个回答

22

你可以使用多个三元运算符:

_moneyCounter > 1000 ? Colors.green : _moneyCounter > 2000 ? Colors.Blue : Colors.red

但为了可读性,我不建议这样做,所以您可以使用一个函数来返回颜色:

Color getMyColor(int moneyCounter) {
 if (moneyCounter == 1000) then {
    return Colors.green;
 } else
  if (moneyCounter == 2000) then {
   return Colors.red;
  }
}

然后使用那个函数:

color: getMyColor(_moneyCounter),

您好,@Raouf Rahiche先生,非常感谢您的帮助。不过,能否请您完成Return方法,这样我就可以跟进了。 - Macaw
请再次检查答案。 - Raouf Rahiche

8

您可以按以下方式使用不同的小部件:

Column(
    children: [
        if (_id == 0) ...[
          Container()
        ] else if(_id == 1)...[
          Text("Hello")
        ] else ...[
          SizedBox(height: 20)
        ],
    ],
 ),


1
没有在文档中看到过这个。省了我大量的时间。谢谢。 - mr_j

1
如果你在列中使用
Column(children:[  if (e["index"] == 1)
              Text(e["text"].toString(),
                  textAlign: TextAlign.center,
                  style: TextStyle(color: Colors.green[900])),
            if (e["index"] == 2)
              Text(e["text"].toString(),
                  textAlign: TextAlign.center,
                  style: TextStyle(color: Colors.green)),
            if (e["index"] == 3)
              Text(e["text"].toString(),
                  textAlign: TextAlign.center,
                  style: TextStyle(color: Colors.amber)),
            if (e["index"] == 4)
              Text(e["text"].toString(),
                  textAlign: TextAlign.center,
                  style: TextStyle(color: Colors.orange)),
            if (e["index"] == 5)
              Text(e["text"].toString(),
                  textAlign: TextAlign.center,
                  style: TextStyle(color: Colors.red)),
          ])

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接