Textfield validation in Flutter

前端 未结 4 1116
你的背包
你的背包 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:03

    I would consider using a TextFormField with a validator.

    Example:

    class MyHomePageState extends State {
      final _formKey = GlobalKey();
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text('TextFormField validator'),
          ),
          body: Form(
            key: _formKey,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                TextFormField(
                  decoration: InputDecoration(
                    hintText: 'Enter text',
                  ),
                  textAlign: TextAlign.center,
                  validator: (text) {
                    if (text == null || text.isEmpty) {
                      return 'Text is empty';
                    }
                    return null;
                  },
                ),
                RaisedButton(
                  onPressed: () {
                    if (_formKey.currentState.validate()) {
                      // TODO submit
                    }
                  },
                  child: Text('Submit'),
                )
              ],
            ),
          ),
        );
      }
    }
    

提交回复
热议问题