Skip to content

Instantly share code, notes, and snippets.

@elliette
Created January 27, 2022 01:43
Show Gist options
  • Save elliette/d31aec75e000b3e2497a10d61bc6da0c to your computer and use it in GitHub Desktop.
Save elliette/d31aec75e000b3e2497a10d61bc6da0c to your computer and use it in GitHub Desktop.
Keyboard shortcut example with / without TextField
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Keyboard Shorcut Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key}) : super(key: key);
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
@override
Widget build(BuildContext context) {
return CounterShortcuts(
onEscDetected: _incrementCounter,
child: Scaffold(
appBar: AppBar(
title: const Text('Demo'),
),
body: Center(
child: Row(
children: <Widget>[
const Spacer(),
// TODO: Uncomment the below. With a TextField,
// if you click into the TextField and out of it
// then clicking ESC no longer works.
//
// const Expanded(
// child: TextField(),
// ),
const Spacer(),
const Text(
'You have pushed ESC this many times:',
),
Text('$_counter'),
const Spacer(),
],
),
),
),
);
}
}
final incrementKeySet = LogicalKeySet(LogicalKeyboardKey.escape);
class IncrementIntent extends Intent {}
class CounterShortcuts extends StatelessWidget {
const CounterShortcuts({
Key? key,
required this.child,
required this.onEscDetected,
}) : super(key: key);
final Widget child;
final VoidCallback onEscDetected;
@override
Widget build(BuildContext context) {
return FocusableActionDetector(
autofocus: true,
shortcuts: {
incrementKeySet: IncrementIntent(),
},
actions: {
IncrementIntent: CallbackAction(onInvoke: (e) => onEscDetected.call()),
},
child: child,
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment