flutter中監聽鍵盤

鲤斌發表於2024-07-15

使用 FocusonKey

class CategoryView extends GetView<CategoryController> {
  const CategoryView({Key? key}) : super(key: key);
  
  @override
  Widget build(BuildContext context) {
      final FocusNode _focusNode = FocusNode();

    return Scaffold(
      appBar: AppBar(
        title: const Text('CategoryView'),
        centerTitle: true,
      ),
      body:
          Focus(
            autofocus: true,
            onKey: (FocusNode focusNode, RawKeyEvent event) {
              if (event is RawKeyDownEvent) {
                print('Key Pressed: ${event.logicalKey.keyLabel}');
                // 在這裡處理鍵盤事件
              }
              return KeyEventResult.handled;
            },
            child: Container(
              width: double.infinity,
              height: double.infinity,
              alignment: Alignment.center,
              child: Text('Tap anywhere to focus and start typing'),
            ),
            focusNode: _focusNode,
          ),
      );
    
  }
}

相關文章