flutter 如何隐藏键盘时,点击屏幕上的任何gestureDetector?

yqlxgs2m  于 2023-03-04  发布在  Flutter
关注(0)|答案(3)|浏览(170)

我有一个带有多个小部件的屏幕。其中一些是可点击的。有一个textInput小部件,当点击它时会打开一个键盘。我想在点击它之外的任何地方时隐藏它。但是如果我点击键盘之外的任何GestureDetector,它会在键盘打开的情况下处理该操作。我想先简单地关闭它。
我试着用gestureDetector包裹整个屏幕,并在其onTap中使用focusNode.unfocus(),但不起作用

hmtdttj4

hmtdttj41#

使用以下代码进行 Package :

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

dddzy1tm2#

如果keyboard已经打开,我想您可以先关闭它,然后再单击其他GestureDetector小部件
比如:

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')),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
wwwo4jvm

wwwo4jvm3#

GestureDetector(
             onTap: () {
             FocusScope.of(context).requestFocus(FocusNode());
       },
)

相关问题