Created
February 23, 2024 00:58
-
-
Save justinmc/0b5c08fa85637422baa84927b7f1ee5f to your computer and use it in GitHub Desktop.
Shows how keyboard shortcuts can interfere with text input, and how to solve that.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/material.dart'; | |
import 'package:flutter/services.dart'; | |
void main() { | |
runApp(const MyApp()); | |
} | |
class MyApp extends StatelessWidget { | |
const MyApp({super.key}); | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
title: 'Flutter Demo', | |
theme: ThemeData( | |
primarySwatch: Colors.blue, | |
), | |
home: const MyHomePage(title: 'Flutter Demo Home Page'), | |
); | |
} | |
} | |
class MyHomePage extends StatelessWidget { | |
const MyHomePage({super.key, required this.title}); | |
final String title; | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
appBar: AppBar( | |
title: Text(title), | |
), | |
body: Center( | |
child: CallbackShortcuts( | |
bindings: <ShortcutActivator, VoidCallback>{ | |
const SingleActivator(LogicalKeyboardKey.keyF): () { | |
print('justin F'); | |
}, | |
const SingleActivator(LogicalKeyboardKey.keyE): () { | |
print('justin E'); | |
}, | |
}, | |
child: const Column( | |
mainAxisAlignment: MainAxisAlignment.center, | |
children: <Widget>[ | |
Shortcuts( | |
shortcuts: <ShortcutActivator, Intent>{ | |
SingleActivator(LogicalKeyboardKey.keyE): DoNothingAndStopPropagationIntent(), | |
}, | |
child: TextField( | |
decoration: InputDecoration( | |
labelText: 'Typing E works, but F is caught by shortcuts.', | |
), | |
), | |
), | |
], | |
), | |
), | |
), | |
); | |
} | |
} |
No problem! Can I ask where you looked before you found this gist? I wonder if there's somewhere in the docs that should explain this more clearly.
@justinmc I think I was looking at this page beforehand, not sure if that'd be the best place to explain it but that's where I was at :)
https://docs.flutter.dev/ui/interactivity/actions-and-shortcuts#overview
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks a bunch for this. I'm trying to implement a ctrl-z for my app which does not interfere with TextField's default ctrl-z, and I'm unpleasantly surprised by how much time I'm spending on this feature. This helps for sure.
I guess at least I'm learning how Focus works in Flutter along the way !