我想要创建一个实时考试应用。这是列表中的一些问题以及这些问题下的一些答案。用户只能从每个问题中选择一个答案。这就是为什么我写了一个 for 循环, for 复选框选择。答案是选择完美,但 if()else 条件的其他选项不能完美工作。我的问题在哪里?请有人帮助我。
这是我的代码-
import 'package:flutter/material.dart';
class AnswerSheet extends StatefulWidget {
@override
_AnswerSheetState createState() => _AnswerSheetState();
}
class _AnswerSheetState extends State<AnswerSheet> {
List answerSheet = [
{
"qNo": 1,
"question": "Who are you ?",
"answer": [
{"ans": "Teacher", "isSelect": false},
{"ans": "Student", "isSelect": false},
{"ans": "Farmer", "isSelect": false},
{"ans": "Developer", "isSelect": false},
]
},
{
"qNo": 2,
"question": "Where are you from ?",
"answer": [
{"ans": "India", "isSelect": false},
{"ans": "Bangladesh", "isSelect": false},
{"ans": "India", "isSelect": false},
{"ans": "China", "isSelect": false},
]
},
{
"qNo": 3,
"question": "Where you born ?",
"answer": [
{"ans": "Dhaka", "isSelect": false},
{"ans": "Barguna", "isSelect": false},
{"ans": "Patuakhali", "isSelect": false},
{"ans": "Gazipur", "isSelect": false},
]
},
];
@override
Widget build(BuildContext context) {
double _width = MediaQuery.of(context).size.width;
double _height = MediaQuery.of(context).size.height;
return Scaffold(
body: Container(
height: _height,
width: _width,
child: SingleChildScrollView(
child: Column(
children: answerSheet.map((questionList) {
return Padding(
padding: const EdgeInsets.all(20.0),
child: Column(
children: [
Row(
children: [
Text(questionList["qNo"].toString()),
SizedBox(
width: 5,
),
Text(
questionList["question"],
style: TextStyle(fontSize: 28),
),
],
),
ListView.builder(
shrinkWrap: true,
physics: NeverScrollableScrollPhysics(),
itemCount: questionList["answer"].length,
itemBuilder: (buildContext, index) {
var answerIndex = questionList["answer"][index];
return Row(
children: [
Checkbox(
value: answerIndex["isSelect"],
onChanged: (value) {
print(
"Length is ${questionList["answer"].length}");
for (var i = 0;
i < questionList["answer"].length;
i++) {
print(
"$i = ${questionList["answer"].indexOf(answerIndex)}");
if (i ==
questionList["answer"].indexOf(
questionList["answer"][index])) {
setState(() {
answerIndex["isSelect"] = value;
});
} else {
setState(() {
questionList["answer"][i]
["is_selected"] = false;
});
}
}
print(answerIndex["isSelect"]);
}),
Container(
color: answerIndex["isSelect"] == true
? Colors.green
: null,
child: Text(
answerIndex["ans"] ?? "",
style: TextStyle(fontSize: 24),
),
)
],
);
})
],
),
);
}).toList(),
),
),
),
);
}
}
答案 0 :(得分:1)
用 isSelect 改变 questionList["answer"][i]['is_select'] 的键
else {
setState(() {
questionList["answer"][i]
["is_selected"] = false;
});
}