I want to make the quiz randomly generated by shuffling them. I created the shuffle class and call the method to shuffle the sample data. But here is the problem, it didn't display randomly as I wanted. I think I am missing something but I have no idea what did I miss. I have called the shuffle method and print them. Can anyone please enlighten me?
//this is the shuffle method and I call the method to shuffle the sample data
List shuffle(List data) {
var random = new Random();
// Go through all elements.
for (var i = data.length - 1; i > 0; i--) {
// Pick a pseudorandom number according to the list length
var n = random.nextInt(i + 1);
List temp = data[i];
data[i] = data[n];
data[n] = temp;
}
return data;
}
main() {
print(shuffle(sample_data));
}
//this is the whole page
class Question {
final int? id, answer;
final String? question;
final List<String>? options;
//final List<String>? audio;
Question({this.id, this.question, this.answer, this.options});
}
const List sample_data = [
{
"id": 1,
"question": "Apakah maksud waqaf?",
"options": ['Berhenti', 'Sambung tanpa nafas baru', 'Sambung', 'Dengung'],
"answer_index": 2,
},
{
"id": 2,
"question": "Apakah pengertian qalqalah dari segi bahasa? ",
"options": ['jelas ', 'lantunan ', 'nyata', 'berhenti'],
"answer_index": 1,
},
{
"id": 3,
"question": "Qalqalah terbahagi kepada ________ jenis.",
"options": ['1', '2', '3', '4'],
"answer_index": 1,
},
{
"id": 4,
"question":
"“Pertemuan antara mim sakinah dengan huruf ba dengan dengung 2 harakat”. ",
"options": [
'Izhar Halqi',
'Wajibul Ghunnah',
'Ikhfa Syafawi',
'Idgham bila ghunnah'
],
"answer_index": 2,
},
];
List shuffle(List data) {
var random = new Random();
// Go through all elements.
for (var i = data.length - 1; i > 0; i--) {
// Pick a pseudorandom number according to the list length
var n = random.nextInt(i + 1);
List temp = data[i];
data[i] = data[n];
data[n] = temp;
}
return data;
}
main() {
print(shuffle(sample_data));
}
Aucun commentaire:
Enregistrer un commentaire