【发布时间】:2019-02-28 19:32:55
【问题描述】:
如果在 TextFormField 中通过验证发现错误消息,我该如何显示?
我正在使用 Stepper 类来处理用户的注册,当尝试使用 setState 实现基本验证时,当前正在验证的文本字段中不会显示错误消息
这是我的代码:
...
class _RegisterState extends State<RegisterPage> {
static TextEditingController _inputController = TextEditingController();
static bool _validate = false;
static String _errorMessage;
static int _currentStep = 0;
static List<Step> _steps = [
Step(
// Title of the Step
title: Text("Phone Number"),
subtitle:
Text('We need your 11 digit phone number to verify your identity!'),
content: TextFormField(
controller: _inputController,
decoration: InputDecoration(
icon: Icon(Icons.phone),
labelText: '01XXXXXXXXX',
errorText: _validate ? _errorMessage : null,
),
maxLength: 11,
keyboardType: TextInputType.number,
),
state: _validate ? StepState.error : StepState.editing,
isActive: true,
),
// Other steps ...
];
@override
Widget build(BuildContext context) {
return CustomScaffold(
title: 'Signup',
body: Stepper(
controlsBuilder: (BuildContext context,
{VoidCallback onStepContinue, VoidCallback onStepCancel}) {
return Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
RaisedButton(
onPressed: onStepContinue,
color: Theme.of(context).accentColor,
child: const Text('Continue'),
),
FlatButton(
onPressed: onStepCancel,
child: const Text('Cancel'),
),
],
);
},
currentStep: _currentStep,
type: StepperType.vertical,
steps: _steps,
// Actions
onStepTapped: (step) {
setState(() {
_currentStep = step;
});
},
onStepCancel: () {
setState(() {
if (_currentStep > 0) {
_currentStep = _currentStep - 1;
} else {
App.router.pop(context);
}
});
},
onStepContinue: () => _validator(),
),
);
}
void _validator() {
if (_currentStep == 0) {
// Validate number
if (_inputController.text.length != 11) {
setState(() {
_validate = true;
_errorMessage = "Phone number must be 11 digits";
});
} else if (!_matchInt()) {
setState(() {
_validate = true;
_errorMessage = "Phone number must be correct";
});
}
}
}
_matchInt() {
RegExp re = RegExp(
r'(\d{11})',
multiLine: false,
);
return re.hasMatch(_inputController.text);
}
void _continue(int currentStep) {
setState(() {
if (_currentStep < _steps.length - 1) {
_currentStep = _currentStep + 1;
} else {
// TODO: Validate data and register a new user
return null;
}
});
}
}
按Continue 按钮不会显示任何错误!
【问题讨论】:
标签: flutter