跳至主要內容

焦点监听键盘

chanchaw小于 1 分钟flutter

概述

需要在获得焦点的情况下监听键盘的单个按键事件

code

把下面代码完整拷贝到新项目的 main.dart 中覆盖所有原来的代码

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

void main() {
  runApp(MyApp());
}
class MyApp extends StatefulWidget {
  
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final FocusNode _focusNode = FocusNode();

  
  void initState() {
    super.initState();
    // 主动请求焦点
    WidgetsBinding.instance.addPostFrameCallback((_) {
      FocusScope.of(context).requestFocus(_focusNode);
    });
  }

  
  void dispose() {
    _focusNode.dispose();
    super.dispose();
  }

  
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: RawKeyboardListener(
            focusNode: _focusNode, // 使用同一个 FocusNode
            onKey: (RawKeyEvent event) {
              if (event is RawKeyDownEvent) {
                print('Key pressed: ${event.logicalKey}');
              }
            },
            child: Container(
              width: 200,
              height: 200,
              color: Colors.blue,
              child: Center(
                child: Text('Press any key (click here first)',
                    style: TextStyle(color: Colors.white)),
              ),
            ),
          ),
        ),
      ),
    );
  }
}