// I have multiple forms because I am using a stepper
// so each step form gets its own validation
bool _validateForm() {
switch (currentStep) {
case 0:
if (userType == null) {
showRadioError();
return false;
}
break;
// ... Other cases / steps
}
return true;
}
// Validate the whole form of the step on button press of "next" button
void onStepContinue(int stepAmount) {
bool isLastStep = (currentStep == stepAmount - 1);
if (isLastStep) {
//Do something with this information
print("FINISHED!");
} else {
if (_validateForm()) {
currentStep += 1;
notifyListeners();
}
}
}
2条答案
按热度按时间xdnvmnnf1#
你可以复制粘贴下面运行完整的代码
您可以使用包https://pub.dev/packages/flutter_form_builder
它支持内置的
validators
,例如您可以直接使用的FormBuilderValidators.required()
您也可以使用
custom validator function
https://pub.dev/packages/flutter_form_builder#custom-validator-function工作演示
全码
yacmzcpb2#
我不想为此使用整个包,但这篇文章帮助我手动解决了这个问题:https://medium.com/free-code-camp/how-to-validate-forms-and-user-input-the-easy-way-using-flutter-e301a1531165
这并不复杂,您基本上只需检查是否选择了一个值: