1// Copyright 2014 The Flutter Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5/// @docImport 'editable_text.dart';
6library;
7
8import 'package:flutter/foundation.dart';
9import 'package:flutter/services.dart';
10
11import 'focus_manager.dart';
12import 'focus_scope.dart';
13import 'framework.dart';
14
15export 'package:flutter/services.dart' show KeyEvent;
16
17/// A widget that calls a callback whenever the user presses or releases a key
18/// on a keyboard.
19///
20/// A [KeyboardListener] is useful for listening to key events and
21/// hardware buttons that are represented as keys. Typically used by games and
22/// other apps that use keyboards for purposes other than text entry.
23///
24/// For text entry, consider using a [EditableText], which integrates with
25/// on-screen keyboards and input method editors (IMEs).
26///
27/// See also:
28///
29/// * [EditableText], which should be used instead of this widget for text
30/// entry.
31class KeyboardListener extends StatelessWidget {
32 /// Creates a widget that receives keyboard events.
33 ///
34 /// For text entry, consider using a [EditableText], which integrates with
35 /// on-screen keyboards and input method editors (IMEs).
36 ///
37 /// The `key` is an identifier for widgets, and is unrelated to keyboards.
38 /// See [Widget.key].
39 const KeyboardListener({
40 super.key,
41 required this.focusNode,
42 this.autofocus = false,
43 this.includeSemantics = true,
44 this.onKeyEvent,
45 required this.child,
46 });
47
48 /// Controls whether this widget has keyboard focus.
49 final FocusNode focusNode;
50
51 /// {@macro flutter.widgets.Focus.autofocus}
52 final bool autofocus;
53
54 /// {@macro flutter.widgets.Focus.includeSemantics}
55 final bool includeSemantics;
56
57 /// Called whenever this widget receives a keyboard event.
58 final ValueChanged<KeyEvent>? onKeyEvent;
59
60 /// The widget below this widget in the tree.
61 ///
62 /// {@macro flutter.widgets.ProxyWidget.child}
63 final Widget child;
64
65 @override
66 Widget build(BuildContext context) {
67 return Focus(
68 focusNode: focusNode,
69 autofocus: autofocus,
70 includeSemantics: includeSemantics,
71 onKeyEvent: (FocusNode node, KeyEvent event) {
72 onKeyEvent?.call(event);
73 return KeyEventResult.ignored;
74 },
75 child: child,
76 );
77 }
78
79 @override
80 void debugFillProperties(DiagnosticPropertiesBuilder properties) {
81 super.debugFillProperties(properties);
82 properties.add(DiagnosticsProperty<FocusNode>('focusNode', focusNode));
83 }
84}
85