Textfield validation in Flutter

前端 未结 4 1122
你的背包
你的背包 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 18:57

    A Minimal Example of what you Want:

    class MyHomePage extends StatefulWidget {
      @override
      MyHomePageState createState() {
        return new MyHomePageState();
      }
    }
    
    class MyHomePageState extends State {
      final _text = TextEditingController();
      bool _validate = false;
    
      @override
      void dispose() {
        _text.dispose();
        super.dispose();
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text('TextField Demo'),
          ),
          body: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text('Error Showed if Field is Empty on Submit button Pressed'),
                TextField(
                  controller: _text,
                  decoration: InputDecoration(
                    labelText: 'Enter the Value',
                    errorText: _validate ? 'Value Can\'t Be Empty' : null,
                  ),
                ),
                RaisedButton(
                  onPressed: () {
                    setState(() {
                      _text.text.isEmpty ? _validate = true : _validate = false;
                    });
                  },
                  child: Text('Submit'),
                  textColor: Colors.white,
                  color: Colors.blueAccent,
                )
              ],
            ),
          ),
        );
      }
    }
    

提交回复
热议问题