Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TextFormField is losing focus - flutter

I am trying to solve form validation in my app. Every time I click to TextFromField, the focus is lost and keyboard hide. I found that problem is with "_formKey". But I need it to validation. How to solve it?

code snippet:

  class _TodoCreateDetailPageState extends State<TodoPage> {
  @override
  Widget build(BuildContext context) {
    final GlobalKey<FormState> _formKey = new GlobalKey<FormState>();

    String _title = widget.todo == null ? "New TODO" : widget.todo.title;
    String _message;

    return new Scaffold(
      appBar: new AppBar(
        title: new Text(_title),
      ),
      floatingActionButton: new FloatingActionButton(
          child: new Icon(Icons.save), onPressed: null),
      body: new Padding(
          padding: new EdgeInsets.all(20.0),
          child: new Form(
              key: _formKey,
              child: new Column(
                children: <Widget>[
                  new TextField(
                    decoration: new InputDecoration(labelText: 'Title'),
                    onChanged: (String value) {
                      _title = value;
                    },
                  ),
                  new TextField(
                    decoration: new InputDecoration(labelText: 'Message'),
                    onChanged: (String value) {
                      _message = value;
                    },
                  )
                ],
              ))),
    );
  }
like image 819
Stepan Avatar asked Jan 22 '26 15:01

Stepan


2 Answers

this issue is due to GlobalKey Initialization with in build()

@override
Widget build(BuildContext context){
    //here is the reason of losing focus.
   final GlobalKey<FormState> _formKey = new GlobalKey<FormState>()
}

Remove it from build and you are all good.

    final GlobalKey<FormState> _formKey = new GlobalKey<FormState>();
    //this will work fine when you move key outside the build();
    @override
    Widget build(BuildContext context){

    }
like image 55
Muhammad Qamar Iqbal Avatar answered Jan 26 '26 18:01

Muhammad Qamar Iqbal


Change StatelessWidget to StatefulWidget works for me, as Derek Lakin said in comments.

like image 22
Will Avatar answered Jan 26 '26 17:01

Will



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!