Update key examples to use Focus widgets instead of RawKeyboardListener (#101537)

This updates the examples for PhysicalKeyboardKey and LogicalKeyboardKey to use Focus widgets that handle the keys instead of using RawKeyboardListener, since that usually leads people down the wrong path. Updated the See Also and added tests as well. Also exposed the `physicalKey` attribute for `tester.sendKeyEvent`.
This commit is contained in:
Greg Spencer
2022-04-08 12:05:41 -07:00
committed by GitHub
parent cae740b903
commit efe76a5373
7 changed files with 182 additions and 54 deletions

View File

@@ -8,61 +8,59 @@ import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() => runApp(const MyApp());
void main() => runApp(const KeyExampleApp());
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
static const String _title = 'Flutter Code Sample';
class KeyExampleApp extends StatelessWidget {
const KeyExampleApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: _title,
home: Scaffold(
appBar: AppBar(title: const Text(_title)),
body: const MyStatefulWidget(),
appBar: AppBar(title: const Text('Key Handling Example')),
body: const MyKeyExample(),
),
);
}
}
class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget({Key? key}) : super(key: key);
class MyKeyExample extends StatefulWidget {
const MyKeyExample({Key? key}) : super(key: key);
@override
State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
State<MyKeyExample> createState() => _MyKeyExampleState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
// The node used to request the keyboard focus.
class _MyKeyExampleState extends State<MyKeyExample> {
// The node used to request the keyboard focus.
final FocusNode _focusNode = FocusNode();
// The message to display.
// The message to display.
String? _message;
// Focus nodes need to be disposed.
// Focus nodes need to be disposed.
@override
void dispose() {
_focusNode.dispose();
super.dispose();
}
// Handles the key events from the RawKeyboardListener and update the
// _message.
void _handleKeyEvent(RawKeyEvent event) {
// Handles the key events from the Focus widget and updates the
// _message.
KeyEventResult _handleKeyEvent(FocusNode node, RawKeyEvent event) {
setState(() {
if (event.logicalKey == LogicalKeyboardKey.keyQ) {
_message = 'Pressed the "Q" key!';
} else {
if (kReleaseMode) {
_message =
'Not a Q: Pressed 0x${event.logicalKey.keyId.toRadixString(16)}';
_message = 'Not a Q: Pressed 0x${event.logicalKey.keyId.toRadixString(16)}';
} else {
// The debugName will only print useful information in debug mode.
// As the name implies, the debugName will only print useful
// information in debug mode.
_message = 'Not a Q: Pressed ${event.logicalKey.debugName}';
}
}
});
return event.logicalKey == LogicalKeyboardKey.keyQ ? KeyEventResult.handled : KeyEventResult.ignored;
}
@override
@@ -73,7 +71,7 @@ class _MyStatefulWidgetState extends State<MyStatefulWidget> {
alignment: Alignment.center,
child: DefaultTextStyle(
style: textTheme.headline4!,
child: RawKeyboardListener(
child: Focus(
focusNode: _focusNode,
onKey: _handleKeyEvent,
child: AnimatedBuilder(
@@ -84,7 +82,7 @@ class _MyStatefulWidgetState extends State<MyStatefulWidget> {
onTap: () {
FocusScope.of(context).requestFocus(_focusNode);
},
child: const Text('Tap to focus'),
child: const Text('Click to focus'),
);
}
return Text(_message ?? 'Press a key');

View File

@@ -4,36 +4,34 @@
// Flutter code sample for PhysicalKeyboardKey
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() => runApp(const MyApp());
void main() => runApp(const KeyExampleApp());
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
static const String _title = 'Flutter Code Sample';
class KeyExampleApp extends StatelessWidget {
const KeyExampleApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: _title,
home: Scaffold(
appBar: AppBar(title: const Text(_title)),
body: const MyStatefulWidget(),
appBar: AppBar(title: const Text('PhysicalKeyboardKey Example')),
body: const MyPhysicalKeyExample(),
),
);
}
}
class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget({Key? key}) : super(key: key);
class MyPhysicalKeyExample extends StatefulWidget {
const MyPhysicalKeyExample({Key? key}) : super(key: key);
@override
State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
State<MyPhysicalKeyExample> createState() => _MyPhysicalKeyExampleState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
class _MyPhysicalKeyExampleState extends State<MyPhysicalKeyExample> {
// The node used to request the keyboard focus.
final FocusNode _focusNode = FocusNode();
// The message to display.
@@ -48,14 +46,21 @@ class _MyStatefulWidgetState extends State<MyStatefulWidget> {
// Handles the key events from the RawKeyboardListener and update the
// _message.
void _handleKeyEvent(RawKeyEvent event) {
KeyEventResult _handleKeyEvent(FocusNode node, RawKeyEvent event) {
setState(() {
if (event.physicalKey == PhysicalKeyboardKey.keyA) {
_message = 'Pressed the key next to CAPS LOCK!';
} else {
_message = 'Wrong key.';
if (kReleaseMode) {
_message = 'Not the key next to CAPS LOCK: Pressed 0x${event.physicalKey.usbHidUsage.toRadixString(16)}';
} else {
// As the name implies, the debugName will only print useful
// information in debug mode.
_message = 'Not the key next to CAPS LOCK: Pressed ${event.physicalKey.debugName}';
}
}
});
return event.physicalKey == PhysicalKeyboardKey.keyA ? KeyEventResult.handled : KeyEventResult.ignored;
}
@override
@@ -66,7 +71,7 @@ class _MyStatefulWidgetState extends State<MyStatefulWidget> {
alignment: Alignment.center,
child: DefaultTextStyle(
style: textTheme.headline4!,
child: RawKeyboardListener(
child: Focus(
focusNode: _focusNode,
onKey: _handleKeyEvent,
child: AnimatedBuilder(
@@ -77,7 +82,7 @@ class _MyStatefulWidgetState extends State<MyStatefulWidget> {
onTap: () {
FocusScope.of(context).requestFocus(_focusNode);
},
child: const Text('Tap to focus'),
child: const Text('Click to focus'),
);
}
return Text(_message ?? 'Press a key');

View File

@@ -0,0 +1,27 @@
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/services.dart';
import 'package:flutter_api_samples/services/keyboard_key/logical_keyboard_key.0.dart' as example;
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('Responds to key', (WidgetTester tester) async {
await tester.pumpWidget(
const example.KeyExampleApp(),
);
await tester.tap(find.text('Click to focus'));
await tester.pumpAndSettle();
expect(find.text('Press a key'), findsOneWidget);
await tester.sendKeyEvent(LogicalKeyboardKey.keyQ);
await tester.pumpAndSettle();
expect(find.text('Pressed the "Q" key!'), findsOneWidget);
await tester.sendKeyEvent(LogicalKeyboardKey.keyB);
await tester.pumpAndSettle();
expect(find.text('Not a Q: Pressed Key B'), findsOneWidget);
});
}

View File

@@ -0,0 +1,26 @@
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/services.dart';
import 'package:flutter_api_samples/services/keyboard_key/physical_keyboard_key.0.dart' as example;
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('Responds to key', (WidgetTester tester) async {
await tester.pumpWidget(
const example.KeyExampleApp(),
);
await tester.tap(find.text('Click to focus'));
await tester.pumpAndSettle();
expect(find.text('Press a key'), findsOneWidget);
await tester.sendKeyEvent(LogicalKeyboardKey.keyQ, physicalKey: PhysicalKeyboardKey.keyA);
await tester.pumpAndSettle();
expect(find.text('Pressed the key next to CAPS LOCK!'), findsOneWidget);
await tester.sendKeyEvent(LogicalKeyboardKey.keyB, physicalKey: PhysicalKeyboardKey.keyB);
await tester.pumpAndSettle();
expect(find.text('Not the key next to CAPS LOCK: Pressed Key B'), findsOneWidget);
});
}