From 0c255bec9a069801fd445577a7f8589154ee022a Mon Sep 17 00:00:00 2001 From: Shawn Date: Thu, 20 Apr 2023 00:01:45 -0600 Subject: [PATCH] Add KeyboardArrowListener to experiment with hz arrow key support on lists --- lib/ui/common/keyboard_arrows_listener.dart | 56 +++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 lib/ui/common/keyboard_arrows_listener.dart diff --git a/lib/ui/common/keyboard_arrows_listener.dart b/lib/ui/common/keyboard_arrows_listener.dart new file mode 100644 index 00000000..fd7d3e90 --- /dev/null +++ b/lib/ui/common/keyboard_arrows_listener.dart @@ -0,0 +1,56 @@ +import 'package:wonders/common_libs.dart'; + +class ArrowDir { + ArrowDir(this.hz, this.vt); + int hz; + int vt; + + bool get isNotZero => hz != 0 || vt != 0; +} + +class KeyboardArrowsListener extends StatefulWidget { + const KeyboardArrowsListener({Key? key, required this.child, required this.onArrow}) : super(key: key); + final Widget child; + final void Function(ArrowDir dir) onArrow; + @override + State createState() => _KeyboardArrowsListenerState(); +} + +class _KeyboardArrowsListenerState extends State { + final FocusNode _focusNode = FocusNode(); + + @override + Widget build(BuildContext context) { + return RawKeyboardListener( + autofocus: true, + focusNode: _focusNode, + onKey: _handleKey, + child: widget.child, + ); + } + + void _handleKey(RawKeyEvent event) { + if (event is! RawKeyDownEvent) return; + if (event.repeat) return; + final arrowDir = ArrowDir(0, 0); + if (event.logicalKey == LogicalKeyboardKey.arrowLeft) { + arrowDir.hz = -1; + } else if (event.logicalKey == LogicalKeyboardKey.arrowRight) { + arrowDir.hz = 1; + } + if (event.logicalKey == LogicalKeyboardKey.arrowUp) { + arrowDir.vt = 1; + } else if (event.logicalKey == LogicalKeyboardKey.arrowDown) { + arrowDir.vt = -1; + } + if (arrowDir.isNotZero) { + widget.onArrow(arrowDir); + } + } + + @override + void dispose() { + _focusNode.dispose(); + super.dispose(); + } +}