How To Prevent Keyboard Being Closed After setState?

Viewed 317

When the button clicked, the condition changes and TextField widget is removed from tree, but the keyboard is closed too. How to keep it open even after the TextField gone ?

bool someCondition;

initState(){
  someCondition = true;
}

...

Row(
   children:[
      someCondition ? TextField() : Text('How to keep keyboard open'),
      FlatButton(child: Text('Click me'), onPress: (){
        setState(() {
           someCondition = false;
        });
      })
   ],
)
1 Answers

You can use Visibility widget and maintain its state.

class HomePage extends StatefulWidget {
  @override
  _HomePage createState() => _HomePage();
}

class _HomePage extends State<HomePage> {
  bool someCondition = true;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Row(
          children: <Widget>[
            Expanded(
              child: Stack(
                children: <Widget>[
                  Visibility(
                    visible: someCondition,
                    maintainAnimation: true,
                    maintainState: true,
                    maintainSize: true,
                    child: TextField(),
                  ),
                  if (!someCondition) const Text('How to keep keyboard open'),
                ],
              ),
            ),
            FlatButton(
              onPressed: () {
                setState(() {
                  someCondition = !someCondition;
                });
              },
              child: const Text('Click me'),
            ),
          ],
        ),
      ),
    );
  }
}
Related