我创建了一个包含 5 个问题的动态表单,每个问题有 5 个单选选项和一个好的答案,我可以使用每个答案的单选按钮来选择
但我无法得到按钮答案:
当我点击单选按钮时我没有改变
class EditQuizPage extends StatefulWidget {
const EditQuizPage({
super.key,
required this.user,
});
final UserModel user;
@override
State<EditQuizPage> createState() => _EditQuizPagetate();
}
class _EditQuizPagetate extends State<EditQuizPage> {
final _formKey = GlobalKey<FormBuilderState>();
final List<Widget> fields = [];
var _newTextFieldId = 0;
String savedValue = '';
@override
void initState() {
savedValue = _formKey.currentState?.value.toString() ?? '';
final textFieldId = _newTextFieldId;
final newTextFieldName = 'Q_${_newTextFieldId++}';
final newTextFieldKey = ValueKey(_newTextFieldId);
fields.add(NewTextField(
key: newTextFieldKey,
name: newTextFieldName,
textFieldId:textFieldId,
onDelete: () {
setState(() {
fields.removeWhere((e) => e.key == newTextFieldKey);
});
},
));
super.initState();
}
@override
Widget build(BuildContext context) {
return FormBuilder(
key: _formKey,
// IMPORTANT to remove all references from dynamic field when delete
clearValueOnUnregister: true,
child: Column(
children: <Widget>[
const SizedBox(height: 20),
...fields,
const SizedBox(height: 10),
Row(
children: <Widget>[
Expanded(
child: ElevatedButton(
child: const Text("Submit"),
onPressed: () {
_formKey.currentState!.saveAndValidate();
setState(() {
savedValue =
_formKey.currentState?.value.toString() ?? '';
});
},
),
),
const SizedBox(width: 20),
(fields.length<4)?
Expanded(
child: ElevatedButton(
child: const Text("Ajouter une question"),
onPressed: () {
final textFieldId = _newTextFieldId;
final newTextFieldName = 'Q_${_newTextFieldId++}';
final newTextFieldKey = ValueKey(_newTextFieldId);
setState(() {
fields.add(NewTextField(
key: newTextFieldKey,
name: newTextFieldName,
textFieldId:textFieldId,
onDelete: () {
setState(() {
fields.removeWhere((e) => e.key == newTextFieldKey);
});
},
));
});
},
),
):const Text(''),
],
),
const Divider(height: 40),
Text('Saved value: $savedValue'),
],
),
);
}
}
class NewTextField extends StatefulWidget {
const NewTextField({
super.key,
required this.name,
required this.textFieldId,
this.onDelete,
});
final String name;
final int textFieldId;
final VoidCallback? onDelete;
@override
State<NewTextField> createState() => _NewTextFieldState();
}
int? selectedOption = 0;
class _NewTextFieldState extends State<NewTextField> {
final List<Widget> options = [];
var _optionsId = 0;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(bottom: 8),
child: Column(
children: [
Row(
children: [
Expanded(
child: FormBuilderTextField(
name: widget.name,
validator: FormBuilderValidators.minLength(4),
decoration: const InputDecoration(
label: Text('Nouvelle question'),
),
),
),
IconButton(
icon: const Icon(Icons.delete_forever),
onPressed: widget.onDelete,
),
]
,
),
...options,
Row(children: [
Expanded(
child: ElevatedButton(
child: const Text("Ajouter une réponse"),
onPressed: () {
final index = _optionsId;
final newOptiondName = 'A_${widget.textFieldId}_${_optionsId++}';
final newOptiondKey = ValueKey(_optionsId);
setState(() {
options.add(NewOptionField(
key: newOptiondKey,
index: index,
name: newOptiondName,
group: widget.textFieldId,
onDelete: () {
setState(() {
options.removeWhere((e) => e.key == newOptiondKey);
});
},
));
});
},
),
),
],)
],
),
);
}
}
class NewOptionField extends StatefulWidget {
const NewOptionField({
super.key,
required this.index,
required this.name,
required this.group,
this.onDelete,
});
final int index;
final String name;
final int group;
final VoidCallback? onDelete;
@override
State<NewOptionField> createState() => _NewOptionFieldState();
}
class _NewOptionFieldState extends State<NewOptionField> {
@override
Widget build(BuildContext context) {
print('${widget.index} $selectedOption');
return Padding(
padding: const EdgeInsets.only(bottom: 8),
child: Row(
children: [
Radio<int>(
value: widget.index,
groupValue: selectedOption,
onChanged: (value) {
setState(() {
selectedOption = value;
print("Button value: $value");
});
},
),
Expanded(
child:FormBuilderTextField(
name: widget.name,
validator: FormBuilderValidators.minLength(3),
decoration: const InputDecoration(
label: Text('Réponse'),
),
),
),
IconButton(
icon: const Icon(Icons.delete_forever),
onPressed: widget.onDelete,
),
],
),
);
}
}
我尝试为刷新状态添加父函数
您似乎正在尝试在 Flutter 中创建一个带有单选按钮的测验应用程序,并希望跟踪用户选择的答案。下面是一个简化示例,说明如何处理更改单选按钮状态并访问 Flutter 中选定的答案。
我创建了一个基本的测验应用程序,用户可以使用单选按钮选择答案,并且您可以轻松检索和打印所选答案。表单小部件用于验证选择和管理状态。
这是代码:
主页小部件:
class HomePage extends StatefulWidget {
const HomePage({super.key});
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
final _formKey = GlobalKey<FormState>();
// Sample quiz question and options
var quizQuestion = QuizQuestion(
question: 'What is the capital of France?',
options: ['Paris', 'London', 'Madrid', 'Rome'],
correctAnswer: 0,
);
// Function to print the selected answer
void printUserAnswer(String? value) {
print(value);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Quiz'),
),
body: Form(
key: _formKey,
child: Column(
children: [
QuestionAndAnswerSection(
quizQuestion: quizQuestion,
onSelectedOption: printUserAnswer,
),
ElevatedButton(
onPressed: () {
if (_formKey.currentState!.validate()) {
_formKey.currentState!.save();
}
},
child: const Text('Submit'),
),
],
),
),
);
}
}
用于显示问题和单选按钮选项的小部件
class QuestionAndAnswerSection extends StatefulWidget {
final QuizQuestion quizQuestion;
final Function(String?) onSelectedOption;
const QuestionAndAnswerSection({super.key, required this.quizQuestion, required this.onSelectedOption});
@override
State<QuestionAndAnswerSection> createState() => _QuestionAndAnswerSectionState();
}
class _QuestionAndAnswerSectionState extends State<QuestionAndAnswerSection> {
@override
Widget build(BuildContext context) {
return FormField(
validator: (String? value) {
if (value == null) {
return 'Please select an option';
}
return null;
},
onSaved: (String? value) {
widget.onSelectedOption(value);
},
builder: (FormFieldState<String> state) => Column(
children: [
Text(widget.quizQuestion.question),
if (state.hasError)
const Text(
'Please select an option',
style: TextStyle(color: Colors.red),
),
...widget.quizQuestion.options.map(
(option) => RadioListTile(
title: Text(option),
value: option,
groupValue: state.value,
onChanged: (String? value) {
state.didChange(value);
},
),
),
],
),
);
}
}
QuizQuestion 类保存问题数据
class QuizQuestion {
final String question;
final List<String> options;
final int correctAnswer;
QuizQuestion({
required this.question,
required this.options,
required this.correctAnswer,
});
}
我希望这个示例可以帮助您构建测验应用程序。如果您还有其他问题,请告诉我!