我有一個自定義的底部導航欄,并根據 selectedIndex 成功更改了背景顏色。我通過三元陳述句來做到這一點:
backgroundColor: selectedIndex == 0
? const Color.fromARGB(255, 0, 52, 35)
: const Color.fromARGB(255, 0, 13, 52),
現在我添加了第三個螢屏,我想按照以下幾行設定一個 if 陳述句:
backgroundColor:
if (selectedIndex == 0)
{const Color.fromARGB(255, 0, 52, 35);}
if (selectedIndex == 1)
{const Color.fromARGB(255, 0, 13, 52);}
if (selectedIndex == 2)
{const Color.fromARGB(255, 87, 0, 54);},
這可能只是一個簡單的語法問題——我是 Flutter 的新手。
uj5u.com熱心網友回復:
您可以使用創建一個單獨的方法switch。
Color getColor(int selectedIndex) {
switch (selectedIndex) {
case 0:
return const Color.fromARGB(255, 0, 52, 35);
case 1:
return const Color.fromARGB(255, 0, 13, 52);
case 2:
return const Color.fromARGB(255, 87, 0, 54);
default:
return Colors.green;
}
}
并使用
backgroundColor: getColor(selectedIndex),
有關開關和外殼的更多資訊
uj5u.com熱心網友回復:
你可以像這樣定義一個函式:
Color getBackgroundColor(int selectedIndex){
if (selectedIndex == 0){
return const Color.fromARGB(255, 0, 52, 35);
}else if (selectedIndex == 1){
return const Color.fromARGB(255, 0, 13, 52);
}else {
return const Color.fromARGB(255, 87, 0, 54);
}
}
并像這樣使用它:
backgroundColor: getBackgroundColor(selectedIndex),
uj5u.com熱心網友回復:
你實際上可以嵌套三元運算式來得到你想要的,比如:
backgroundColor: selectedIndex == 0
? const Color.fromARGB(255, 0, 52, 35)
: selectedIndex == 1
? const Color.fromARGB(255, 0, 13, 52)
: const Color.fromARGB(255, 87, 0, 54),
盡管我會更多地推薦 Yeasin Sheikh 的答案,尤其是如果您想添加更多索引
uj5u.com熱心網友回復:
實作此目的的另一種方法是使用 aMap<int, Color>并將索參考作key地圖的 a:
Color getColor(int selectedIndex) {
return const <int, Color>{
0: Color.fromARGB(255, 0, 52, 35),
1: Color.fromARGB(255, 0, 13, 52),
2: Color.fromARGB(255, 87, 0, 54),
}[selectedIndex] ?? Colors.green; // default value
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/517985.html
