I am working on Flutter TextField
widget. I want to show an error message below the TextField
widget if the user does not fill that TextField
You can do something like this
class _validateTextField extends State {
TextEditingController userNameController = TextEditingController();
bool userNameValidate = false;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
TextField(
controller: userNameController,
decoration: InputDecoration(
labelText: 'Enter Username',
errorText: isUserNameValidate ? 'Please enter a Username' : null
),
),
SizedBox(height: 50,),
OutlineButton(
onPressed: () {
validateTextField(userNameController.text);
},
child: Text('Validate'),
textColor: Colors.blue,
),
]
)
),
);
}
}
Create Function - This function will validate whether the value you entered is validate or not. And call it at the click of a submit or validate button
bool validateTextField(String userInput) {
if (userInput.isEmpty) {
setState(() {
isUserNameValidate = true;
});
return false;
}
setState(() {
isUserNameValidate = false;
});
return true;
}