如何在Flutter/iOS上显示键盘(使用KeyboardListener但不使用TextField)?

ntjbwcob  于 2022-11-17  发布在  Flutter
关注(0)|答案(1)|浏览(328)

如何在Flutter中使用KeyboardListener显示屏幕键盘?我尝试附加一个FocusNode并调用focusNode.requestFocus(),但似乎不起作用。此问题发生在Flutter 3.3.1中,它运行在真实的设备上。示例代码如下:

void main() {
  runApp(const KeyListenerTest());
}

class KeyListenerTest extends StatefulWidget {
  const KeyListenerTest({Key? key}) : super(key: key);

  @override
  State<KeyListenerTest> createState() => KeyListenerTestState();
}

class KeyListenerTestState extends State<KeyListenerTest> {
  late final FocusNode _keyboardShortcutsFocus = FocusNode();

  @override
  void initState() {
    super.initState();
    _keyboardShortcutsFocus.requestFocus();
  }

  void _handleKeyboardShortcuts(KeyEvent keyEvent) {
    print('on key pressed detected with ${keyEvent.logicalKey.keyLabel}');
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: KeyboardListener(
        autofocus: true,
        focusNode: _keyboardShortcutsFocus,
        onKeyEvent: _handleKeyboardShortcuts,
        child: Scaffold(
          body: Center(
            child: GestureDetector(
              onTap: () {
                print('ontap');
                _keyboardShortcutsFocus.requestFocus();
              },
              child: Text('Press here!'),
            ),
          ),
        ),
      ),
    );
  }
}
z9ju0rcb

z9ju0rcb1#

还有另一种办法:使用TextField,它具有名为autoFocus属性,您还可以使用readOnly: true管理编辑。

TextField(
   focusNode: _keyboardShortcutsFocus,,
   autofocus: true,
   readOnly: true
);

相关问题