Textfield validation in Flutter

2020-02-24 12:03发布

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. I only have to use TextField Widget not TextFormField in this case.

标签: dart flutter
2条回答
一纸荒年 Trace。
2楼-- · 2020-02-24 12:21

Adding to @anmol answer. TextFormField is also a better option for validation.

Flutter handles error text itself, so we don't require to use variable _validate. It will check at runtime whether you satisfied the condition or not.

final confirmPassword = TextFormField(
      controller: widget.confirmPasswordController,
      obscureText: true,
      decoration: InputDecoration(
        prefixIcon: Icon(Icons.lock_open, color: Colors.grey),
        hintText: 'Confirm Password',
        errorText: validatePassword(widget.confirmPasswordController.text),
        contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),
      ),
    );

 String validatePassword(String value) {
      if (!(value.length > 5) && value.isNotEmpty) {
        return "Password should contains more then 5 character";
      }
      return null;
    }

Note: User must add at least one character to get this error message.

查看更多
▲ chillily
3楼-- · 2020-02-24 12:23

A Minimal Example of what you Want:

class MyHomePage extends StatefulWidget {
  @override
  MyHomePageState createState() {
    return new MyHomePageState();
  }
}

class MyHomePageState extends State<MyHomePage> {
  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: <Widget>[
            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,
            )
          ],
        ),
      ),
    );
  }
}
查看更多
登录 后发表回答