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?
CodePudding user response:
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';
});
}
}
CodePudding user response:
1º: I stored a new field in the database with the name of the field of the correct answer: sol
2º: created a int where the value stored will be the index of the correct option in the alternatives list:
int indexOfTheRightOption = alternatives.indexWhere((element) => element == output['sol']);
3º: _selectedIndex int and onSelected function:
int? _selectedIndex;
_onSelected(int index) {
setState(() {
_selectedIndex = index;
});
}
4º Color function:
Color color(int? selectedIndex, int indexOfOPtion, int i) {
if (selectedIndex == null) {
return Colors.grey;
}
if (selectedIndex == i && indexOfOPtion == selectedIndex) {
return Colors.green;
}
if (selectedIndex == i && indexOfOPtion != selectedIndex) {
return Colors.red;
}
return Colors.grey;
}
5º add the function to color in TExtStyle:
color: color(_selectedIndex, indexOfTheRightOption, i)
6º onTap function:
onTap: () {
_onSelected(i);
}
Extra: when navigating to next ou previous page, set the state of _selectedIndex to null:
setState(() {
_selectedIndex = null;
});
