0

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

  • 1
    Does this answer your question? [How to hide soft input keyboard on flutter after clicking outside TextField/anywhere on screen?](https://stackoverflow.com/questions/51652897/how-to-hide-soft-input-keyboard-on-flutter-after-clicking-outside-textfield-anyw) – Xuuan Thuc Mar 01 '23 at 08:03

2 Answers2

1

Wrap with following code:

GestureDetector(
             onTap: () {
              /* Hide Keyboard */
             FocusManager.instance.primaryFocus?.unfocus();
       },
)

Tejaswini Dev
  • 1,311
  • 2
  • 8
  • 20
0

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')),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
krishnaacharyaa
  • 14,953
  • 4
  • 49
  • 88