如果通过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
按钮不会显示任何错误!
答案 0 :(得分:1)
与其在构建方法外部创建Step
,不应该在构建方法内部。
确保您正在TextField
内构建StateFullWidget
小部件
您还可以使用onChange
TextField(
controller: textEditingController,
onChanged: (String string){
print(string);
print(_validate);
if (string.length < 3) {
setState(() {
_validate = true;
});
}else {
setState(() {
_validate = false;
});
}
},
keyboardType: TextInputType.number,
decoration: new InputDecoration(hintText: 'Enter the number',
errorText: _validate ? 'here' : 'change'),
)