[英]Change color ListView.Builder onPressed Flutter
我想改變顏色。 如果我選擇值為“einamal”(真)的索引,它將是綠色,否則(假)紅色。
List<String> _choices = <String>[ 'einmal','zweimal', 'dreimal', 'viemal' ];
List<bool> _hasBeenPressed = [true, false, false, false];
Widget _buildChoice() {
return Container(
height: MediaQuery.of(context).size.height/4,
child: ListView.builder(
itemCount: _choices.length,
itemBuilder: (BuildContext context, int index)
{
return RaisedButton(
child: new Text(_choices[index]),
textColor: _hasBeenPressed[index] ? Colors.white : Colors.green,
color: _hasBeenPressed[index] ? Colors.green : Colors.white,
onPressed: () =>
{
setState(() {
if(_choices[index] == 'einmal') {
_hasBeenPressed[index] = !_hasBeenPressed[index];
}
})
},
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(30.0)
),
);
}
),
);
}
您需要另一個變量來存儲您的實際答案,在您的情況下,它將是,
String answer = "einmal";
現在,您只需要一個String
來存儲用戶選擇的選項而不是列表,就像這樣,
String selected = "";
現在,每當用戶選擇一個選項時,更新您的selected
,就像這樣,
onPressed: () => {
setState(() {
selected = _choices[index];
})
},
現在,用它來獲得正確的顏色,
textColor: selected == _choices[index] ? Colors.white : Colors.green,
color: selected == _choices[index]
? (selected == answer ? Colors.green : Colors.red)
: Colors.white,
完整的代碼,
List<String> _choices = <String>['einmal', 'zweimal', 'dreimal', 'viemal'];
String answer = "einmal";
String selected = "";
Widget _buildChoice() {
return Container(
height: MediaQuery.of(context).size.height / 4,
child: ListView.builder(
itemCount: _choices.length,
itemBuilder: (BuildContext context, int index) {
return RaisedButton(
child: new Text(_choices[index]),
textColor:
selected == _choices[index] ? Colors.white : Colors.green,
color: selected == _choices[index]
? (selected == answer ? Colors.green : Colors.red)
: Colors.white,
onPressed: () => {
setState(() {
selected = _choices[index];
})
},
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(30.0)),
);
}),
);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.