How to hide soft input keyboard on flutter after clicking outside TextField/anywhere on screen?

后端 未结 16 1961
甜味超标
甜味超标 2020-12-08 01:54

Currently, I know the method of hiding the soft keyboard using this code, by onTap methods of any widget.

FocusScope.of(context).requestFocus(new         


        
相关标签:
16条回答
  • 2020-12-08 02:09

    Just as a small side note:

    If you use ListView its keyboardDismissBehavior property could be of interest:

    ListView(
      keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,
      children: [],
    )
    
    0 讨论(0)
  • 2020-12-08 02:09

    FocusScopeNode currentFocus = FocusScope.of(context);

        if (!currentFocus.hasPrimaryFocus) {
          currentFocus.unfocus();
        }
    

    You should check here https://flutterigniter.com/dismiss-keyboard-form-lose-focus/

    0 讨论(0)
  • 2020-12-08 02:12
    GestureDetector(
      onTap: () {
            FocusScope.of(context).requestFocus(FocusNode());
      },
      behavior: HitTestBehavior.translucent,
      child: rootWidget
    )
    
    0 讨论(0)
  • 2020-12-08 02:12

    If you want to do this "the right way", use Listener instead of GestureDetector.

    GestureDetector will only work for "single taps", which isn't representative of all possible gestures that can be executed.

    Listener(
      onPointerDown: (_) {
        FocusScopeNode currentFocus = FocusScope.of(context);
        if (!currentFocus.hasPrimaryFocus) {
          currentFocus.focusedChild.unfocus();
        }
      },
      child: MaterialApp(...),
    );
    
    0 讨论(0)
  • 2020-12-08 02:14

    Wrap whole screen in GestureDetector as

    new Scaffold(
    
      body: new GestureDetector(
          onTap: () {
            // call this method here to hide soft keyboard
            FocusScope.of(context).requestFocus(new FocusNode());
          },
        child: new Container(
           -
           -
           -
            )
       )
    
    0 讨论(0)
  • 2020-12-08 02:15
    onPressed: () {
        FocusScope.of(context).unfocus();
    },
    

    This works for me.

    0 讨论(0)
提交回复
热议问题