Widget OptionField(String a, String b, Key key, int s) {
return AnimatedContainer(
key: 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: (s == 1)
? Colors.green
: (s == 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),
),
]),
));
THIS IS THE WIDGET WHICH IS BEING CALLED IN THE LISTVIEW MULTIPLE TIMES
Expanded(
child: Column(
children: [
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;
});
ca ;
} else {
setState(() {
isCorrect = 2;
});
}
if (questionCounter == questionMaxLength - 1) {
openDialog('Quiz Completed!',
'Click on the Submit button below to see the Result');
} else {
Timer(
const Duration(seconds: 2),
() => setState(() {
questionCounter ;
isCorrect = 0;
// optionColor = Colors.white;
}));
}
},
child: OptionField(
option[index],
widget.QandAnsList[questionCounter]
.Answers[index],
UniqueKey(),
isCorrect),
);
},
)
],
),
)
THIS IS THE LISTVIEW CODE IN WHICH I'M ASSIGNING UNIQUE KEYS TO THE WIDGET. BASICALLY WHAT I WANT IS TO CHANGE THE COLOR OF THE SPECIFIC WIDGET BASED ON RIGHT OR WRONG ANSWER BUT WHAT HAPPENS IS THAT IT CHANGES THE COLOR OF ALL WIDGETS DESPITE ASSIGNING THEM UNIQUE KEYS.
CodePudding user response:
setState() method rebuilds the state or in other words, it calls Widget build(ctx) method, so your listview is builded everytime. Instead try assigning each question a state and then change particular question's state to show true/false for that particular question
CodePudding user response:
try removing the global isCorrect
variable and then define one inside the itembuilder.
itemBuilder: (context, index) {
int isCorrect = 2;
and the rest code will be the same.