'Change a List item color if the selected one matches the solution
I store the alternatives as fields option1, option2, ... in the database.
The answer is stored as solution.
var to generate a list with the numberOfOptions stored:
var alternatives = List<String>.generate(output['numberOfOptions'],(int index) => 'option${index + 1}');
ListView.builder:
ListView.builder(
physics:
const NeverScrollableScrollPhysics(),
itemCount: alternatives.length,
itemBuilder: (ctx, i) {
return GestureDetector(
child: Text(
output[alternatives[i]],
style: const TextStyle(
color: Colors.grey),
),
onTap: () {
if (output['solution'] ==
output[alternatives[i]]) {
setState(() {
isCorrect = true;
});
} else {
setState(() {
isCorrect = false;
});
}
}
);
})
I'm having difficulties trying to change the color of the alternative if the solution matches the selected alternative. How can I do it?
Solution 1:[1]
Create a mechanism to keep track of the answers:
var answers = List<String>.generate(output['numberOfOptions'],(int index) => 'unanswered');
Base the color on the answer:
Text(
output[alternatives[i]],
style: TextStyle(
color: answers[i] == 'unanswered'
? Colors.grey
: answers[i] == 'correct'
? Colors.green
: Colors.red,
),
)
Update answer in onTap:
onTap: () {
if (output['solution'] == output[alternatives[i]]) {
setState(() {
answers[i] = 'correct';
});
} else {
setState(() {
answers[i] = 'incorrect';
});
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
