Issue
I'm making a custom TextFormField Widget which will be used multiple times. How do I validate a single TextFormField without validating any other TextFormField that are in the same list/row/column.
Widget timeTextField (TextEditingController controller){
return TextFormField(
controller: controller,
validator: (String userInput){
if(userInput.isEmpty){return 'Need to input time';}
},
onFieldSubmitted: (String userInput){
setState(() {
debugPrint(userInput);
controller.text = "amout";
debugPrint(controller.text);
});
},
);
}
It validates when the user presses submit on the keyboard, if the TextFormField is empty it sends a validation error only to that TextFormField which the user pressed submit on.
Solution
Validation in TextField
s happen based on the Form
they are placed in (and not Column
or Row
or List
). To validate TextFields separately put them in different forms, assign different keys and call _formKey.currentState.validate
separately.
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
final GlobalKey<FormState> _form1Key = GlobalKey();
final GlobalKey<FormState> _form2Key = GlobalKey();
final GlobalKey<FormState> _form3Key = GlobalKey();
return Scaffold(
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Form(
key: _form1Key,
child: TextFormField(
validator: (value) {
if (value.isEmpty) return "Cannot be empty";
},
),
),
Form(
key: _form2Key,
child: TextFormField(
validator: (value) {
if (value.isEmpty) return "Cannot be empty";
},
),
),
Form(
key: _form3Key,
child: TextFormField(
validator: (value) {
if (value.isEmpty) return "Cannot be empty";
},
),
),
],
),
floatingActionButton: FloatingActionButton(onPressed: () {
_form2Key.currentState.validate();
}),
);
}
}
Answered By - Ajil O.
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.