Removing keyboard focus on multiple buttons pressed

Viewed 1025

I'm trying to hide keyboard when tapped everywhere outside of textField. So I wrapped Scaffold with GestureDetector and set onTap with unfocused(). That works well however when a button is pressed then the keyboard is still active

  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () => FocusScope.of(context).unfocus(),
      child: Scaffold(
        appBar: AppBar(
          actions: <Widget>[FlatButton(child: Text('Done'), onPressed: () {})],
        ),
        body: Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            FlatButton(
              child: Text('something'),
              onPressed: () {},
            ),
            TextField(),
          ],
        ),
      ),
    );
  }

Is there any way to remove the focus without adding that unfocused in onTap of all buttons.. Reason is I've got many buttons there and some has even onLogTap set so there would be a lot of duplicate codes

2 Answers

You need to also add code for hide keyboard inside onPressed() method of FlatButton

FlatButton(
    child: Text('something'),
    onPressed: () {
    FocusScope.of(context).unfocus();
   },   
),

was hoping for some solution where I wouldn't need so many duplicate codes to do one thing.

AFAIK that is not possible because the click event of GestureDetector widget and click event of FlatButton both are different,

You are registering different/separate click event of FlatButton that's why your keyboard is not hiding when you click on FlatButton

Now the reason why your keyboard not hiding when pressed on buttons

Because the click event of your GestureDetector widget if overridden by the click event of your FlatButton

SOLUTION

You can do one thing, create a common method to hide the keyboard, and call that method to from button click

By thinking a little outside of the box I have managed to hide keyboard on all taps by modifying GestureDetector..

  Widget build(BuildContext context) {
    return GestureDetector(
      onPanDown: (pd) {FocusScope.of(context).unfocus();}, //<- replaced
      child: Scaffold(
        appBar: AppBar(
          actions: <Widget>[FlatButton(child: Text('Done'), onPressed: () {})],
        ),
        body: Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            FlatButton(
              child: Text('something'),
              onPressed: () {},
            ),
            TextField(),
          ],
        ),
      ),
    );
  }

Now the keyboard will hide on taping everywhere outside of the TextField even on Buttons click.. No need to hide it in each button click. Please if you know about better solution then let me know

UPDATE: This solution will create exception when tap on already focused TextField

Related