英文:
Flutter Form widget not validating all fields in the form
问题
我有一个IntlPhoneWidget和一个文本字段(widget)位于一个Stepper(widget)内。当我按下继续按钮时,它只验证IntlPhoneWidget而不验证文本字段。另外,如果这些字段为空,我该如何为Stepper内的每个字段添加自定义验证消息?
这是我的代码-
@override
Widget build(BuildContext context) {
return Scaffold(
body: Form(
key: _formKey,
child: Stepper(
currentStep: _currentStepper,
onStepContinue: _continueStep,
steps: [
Step(
title: const Text('输入您的姓名和电话号码'),
content: Column(
children: [
TextField(
controller: _displayNameTextFieldController,
),
IntlPhoneField(
decoration: const InputDecoration(
labelText: '电话号码',
),
onChanged: (phone) {
setState(() {
_phoneNumber = (phone.completeNumber).trim();
});
},
)
],
),
)
],
),
),
);
}
void _continueStep() {
if (_currentStepper == 0) {
_formKey.currentState?.validate();
}
}
英文:
I have a IntlPhoneWidget and a textfield widget inside of a stepper widget. When I press the continue button it only validates the intlphonewidget and not the textfield. Also how do I put in a custom validation message for each of the fields inside of the stepper if those fields are empty?
Here is my code-
@override
Widget build(BuildContext context) {
return Scaffold(
body: Form(
key: _formKey,
child: Stepper(
currentStep: _currentStepper,
onStepContinue: _continueStep,
steps: [
Step(
title: const Text('Enter your name and phone number'),
content: Column(
children: [
TextField(
controller: _displayNameTextFieldController,
),
IntlPhoneField(
decoration: const InputDecoration(
labelText: 'Phone Number',
),
onChanged: (phone) {
setState(() {
_phoneNumber = (phone.completeNumber).trim();
});
},
)
],
),
)
],
),
),
);
}
void _continueStep() {
if (_currentStepper == 0) {
_formKey.currentState?.validate();
}
}
答案1
得分: 2
这是因为 IntlPhoneField
具有内置的 validator
,但 TextField
没有,如果您想为第一个字段也设置 validator
,您需要改用 TextFormField
并像这样设置 validator
:
TextFormField(
controller: _displayNameTextFieldController,
validator: (value) {
if (value != null && value.isEmpty) {
return '填写姓名字段';
}
return null;
},
)
英文:
This happened because the IntlPhoneField
has built-in validator
, but TextField doesn't, if you want to have validator
for first field too , you need to use TextFormField
instead and set the validator
like this:
TextFormField(
controller: _displayNameTextFieldController,
validator: (value) {
if (value != null && value.isEmpty) {
return 'fill name field';
}
return null;
},
)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论