I am creating a quiz app where upon tapping on an index, its color should change based upon the answer. when I select an index, all the indexes inside the ListView change colors.
HERE is the code for my 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,
),
);
},
)),
HERE is the code for the OptionField widget :
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),
),
]),
));
}
I tried everything I could but nothing is working thus far. I'm still unable to change the color of the selected index
CodePudding user response:
you could introduce another variable to indicate which index was tapped. for example
int tappedIndex = -1;
then change your item builder to
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,
),
);
},