我正在创建一个测验应用程序,在点击索引时,它的颜色应该根据答案而变化。当我选择一个索引时,ListView中的所有索引都会改变颜色。
下面是我的listview的代码:ListView.separated(
scrollDirection: Axis.vertical,
shrinkWrap: true,
itemCount: 4,
separatorBuilder: (context, index) {
return SizedBox(
height: 7,
);
},
itemBuilder: (context, index) {
return InkWell(
onTap: () {
if (widget.QandAnsList[questionCounter]
.Answers[index] ==
widget
.QandAnsList[questionCounter].CorrectAnswer) {
setState(() {
isCorrect = 1;
});
} else {
setState(() {
isCorrect = 2;
});
}
},
child: OptionField(
option[index],
widget.QandAnsList[questionCounter].Answers[index],
ValueKey(index.toString()),
isCorrect,
),
);
},
)),
下面是OptionField小部件的代码:
Widget OptionField(
String a,
String b,
ValueKey key,
int isCorrect,
) {
return AnimatedContainer(
key: ValueKey(key),
duration: Duration(seconds: 1),
height: MediaQuery.of(context).size.height * 0.07,
width: MediaQuery.of(context).size.width * 0.9,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(28),
color: (isCorrect == 1)
? Colors.green
: (isCorrect == 2)
? Colors.red
: Colors.white),
child: Padding(
padding: EdgeInsets.fromLTRB(8, 0, 8, 0),
child: Row(children: [
Container(
alignment: Alignment.center,
height: MediaQuery.of(context).size.height * 0.055,
width: MediaQuery.of(context).size.height * 0.055,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(25),
color: Color.fromARGB(255, 255, 123, 0)),
child: Text(
'$a',
style: TextStyle(
color: Colors.white,
fontSize: 24,
fontWeight: FontWeight.bold),
),
),
SizedBox(
width: 15,
),
Text(
'$b',
style: TextStyle(
color: Colors.black,
fontSize: 16,
fontWeight: FontWeight.bold),
),
]),
));
}
我试了我能做的一切,但到目前为止都没有效果。我仍然无法改变选定索引
的颜色可以引入另一个变量来指示选中了哪个索引。例如
int tappedIndex = -1;
然后将项目构建器更改为
itemBuilder: (context, index) {
return InkWell(
onTap: () {
if (widget.QandAnsList[questionCounter]
.Answers[index] ==
widget
.QandAnsList[questionCounter].CorrectAnswer) {
setState(() {
tappedIndex = index;
isCorrect = 1;
});
} else {
setState(() {
tappedIndex = index;
isCorrect = 2;
});
}
},
child: OptionField(
option[index],
widget.QandAnsList[questionCounter].Answers[index],
ValueKey(index.toString()),
tappedIndex == index ? isCorrect : 0,
),
);
},