簡體   English   中英

如何在沒有 TextField 的情況下使用 KeyboardListener 在 Flutter/iOS 上顯示鍵盤?

[英]How do you show keyboard on Flutter/iOS with KeyboardListener without TextField?

在 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!'),
            ),
          ),
        ),
      ),
    );
  }
}

還有另一種方法:使用TextField它具有名為autoFocus的屬性,您還可以使用readOnly: true來管理編輯。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM