Textfield validation in Flutter

前端 未结 4 1112
你的背包
你的背包 2020-12-08 18:13

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

4条回答
  •  北海茫月
    2020-12-08 19:06

    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;
      }
    

提交回复
热议问题