改变容器边框颜色



我有四个容器,想做一个测验应用程序。我需要改变容器边框颜色时选择。例如,当我只选择正确的选项时,所选择的选项颜色需要更改为绿色。当我选择了错误的选项时,错误的选项需要显示为红色,同时正确的答案也需要显示为绿色。我正在努力如何使代码改变颜色。告诉我正确的方法。我想做的就是在点击

时改变容器边框的颜色。
SizedBox(height: 20),
Expanded(
child: Container(
margin: EdgeInsets.only(bottom: 10),
padding: EdgeInsets.all(8.0),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(25.0),
), //boxdecoration
child: Column(
children: [
SizedBox(height: 10),
Container(
margin: EdgeInsets.only(top: 10),
padding: EdgeInsets.all(8.0),
decoration: BoxDecoration(
border: Border.all(color: Colors.grey),
borderRadius: BorderRadius.circular(15),
), //decoration
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'Answer 1', style: TextStyle(color: Colors.grey, fontSize: 16), //textStyle
), //text
Container(
height: 26,
width: 26,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(50.0),
border: Border.all(color: Colors.grey),
), //boxdecoration
), //container
], //widget
), //row
), //container

首先选定的索引为空。同时,我们知道正确答案的索引。为了存档,我们可以在状态类中包含两个变量。

int _rightAnswerIndex = 2;
int? tappedIndex;

对于每个按下的答案,我们将分配tappedIndex

setState(() {
tappedIndex = index;
});
},`

要控制边框的颜色,首先我们将检查索引是否被选中,

  • 如果不选中,只传递默认颜色或空颜色,或只传递Colors.transparent
  • 如果选中,检查选项是否正确,然后分配颜色

color: tappedIndex != null
? _rightAnswerIndex == index 
? Colors.green
: Colors.red
: Colors.transparent,
),,

带有容器的完整状态类


class _AnimTestState extends State<AnimTest> {
int _rightAnswerIndex = 2;
int? tappedIndex;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
children: [
...List.generate(
4,
(index) => Padding(
padding: const EdgeInsets.all(8.0),
child: InkWell(
onTap: () {
setState(() {
tappedIndex = index;
});
},
child: Container(
decoration: BoxDecoration(
border: Border.all(
color: tappedIndex != null
? _rightAnswerIndex == index 
? Colors.green
: Colors.red
: Colors.transparent,
),
),
child: Text("Answer $index"),
),
),
),
),
],
),
),
);
}
}