Flutter 按键事件监听 RawKeyboardListener

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

class RawKeyTestPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _RawKeyTestState();
}

class _RawKeyTestState extends State<RawKeyTestPage> {
  @override
  void initState() {
    super.initState();
  }

  String _value = '';

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
      appBar: AppBar(title: Text('RawKeyboardListener Page')),
      body: RawKeyboardListener(
              autofocus: true,
              onKey: (event) {
                if (event.runtimeType == RawKeyDownEvent) {
                  if(event.data is RawKeyEventDataAndroid){
                    RawKeyEventDataAndroid datga = event.data as RawKeyEventDataAndroid;
                    ///获取按键键值 keycode
                    _value = datga.keyCode.toString();
                    setState(() {

                    });
                    // print('flutter down'+datga.keyCode.toString());
                  }
                }
              },
              focusNode: FocusNode(),
              child:  Text(_value),
            )
          ,
    ));
  }

  @override
  void dispose() {
    super.dispose();
  }
}

上一篇:Flutter 命名路由以及命名路由传参数


下一篇:Dart语法基础系列三《常量变量》