如何在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!'),
),
),
),
),
);
}
}
1条答案
按热度按时间z9ju0rcb1#
还有另一种办法:使用
TextField
,它具有名为autoFocus
属性,您还可以使用readOnly: true
管理编辑。