skip to Main Content

I have a screen with multiple widgets. Some of them are clickable. There is one textInput widget that opens a keyboard when clicked on it. I want to hide it whenever clicked anywhere outside it. But if i click on any GestureDetector outside keyboard, then it handles that action with keyboard open. I want to simply close it first.

I tried wrapping my whole screen in a gestureDetector and use focusNode.unfocus() in its onTap, but it didn’t work

3

Answers


  1. I guess you can close the keyboard if already open before clicking on another GestureDetector widgets

    Something like:

    class MyWidget extends StatefulWidget {
      @override
      _MyWidgetState createState() => _MyWidgetState();
    }
    
    class _MyWidgetState extends State<MyWidget> {
      final _textController = TextEditingController();
      bool _isKeyboardOpen = false;
    
      @override
      Widget build(BuildContext context) {
        return GestureDetector(
          onTap: () {
            // Close keyboard if it is open
            if (_isKeyboardOpen) {
              FocusScope.of(context).unfocus();
              _isKeyboardOpen = false;
            }
          },
          child: Scaffold(
            appBar: AppBar(title: Text('My Widget')),
            body: Column(
              children: [
                TextField(
                  controller: _textController,
                  onTap: () {
                    // Set keyboard open flag to true when text input is tapped
                    _isKeyboardOpen = true;
                  },
                ),
                GestureDetector(
                  onTap: () {
                    // Handle tap on this widget
                    print('Tapped on GestureDetector');
                  },
                  child: Container(
                    width: 100,
                    height: 100,
                    color: Colors.blue,
                    child: Center(child: Text('Clickable widget')),
                  ),
                ),
              ],
            ),
          ),
        );
      }
    }
    
    Login or Signup to reply.
  2. Wrap with following code:

    GestureDetector(
                 onTap: () {
                  /* Hide Keyboard */
                 FocusManager.instance.primaryFocus?.unfocus();
           },
    )
    
    
    Login or Signup to reply.
  3. GestureDetector(
                 onTap: () {
                 FocusScope.of(context).requestFocus(FocusNode());
           },
    )
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search