Skip to content

Instantly share code, notes, and snippets.

@csells
Created May 19, 2021 03:19
Show Gist options
  • Select an option

  • Save csells/8313557b05636f657f69a5d41db97265 to your computer and use it in GitHub Desktop.

Select an option

Save csells/8313557b05636f657f69a5d41db97265 to your computer and use it in GitHub Desktop.
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) => MaterialApp(
title: 'Flutter TextField Key Binding Demo',
home: Scaffold(body: UnforgivingTextField()),
);
}
/// A text field that clears itself if the user tries to back up or correct
/// something.
class UnforgivingTextField extends StatefulWidget {
@override
State<UnforgivingTextField> createState() => _UnforgivingTextFieldState();
}
class _UnforgivingTextFieldState extends State<UnforgivingTextField> {
// The text editing controller used to clear the text field.
late TextEditingController controller;
@override
void initState() {
super.initState();
controller = TextEditingController();
}
@override
Widget build(BuildContext context) => Shortcuts(
shortcuts: <LogicalKeySet, Intent>{
// This overrides the left arrow key binding that the text field normally
// has in order to move the cursor back by a character. The default is
// created by the MaterialApp, which has a DefaultTextEditingShortcuts
// widget in it.
LogicalKeySet(LogicalKeyboardKey.arrowLeft): const ClearIntent(),
// This binds the delete and backspace keys to also clear the text field.
// You can bind any key, not just those already bound in
// DefaultTextEditingShortcuts.
LogicalKeySet(LogicalKeyboardKey.delete): const ClearIntent(),
LogicalKeySet(LogicalKeyboardKey.backspace): const ClearIntent(),
},
child: Actions(
actions: <Type, Action<Intent>>{
// This binds the intent that indicates clearing a text field to the
// action that does the clearing.
ClearIntent: ClearAction(controller: controller),
},
child: Center(child: TextField(controller: controller)),
),
);
}
/// An intent that is bound to ClearAction.
class ClearIntent extends Intent {
const ClearIntent();
}
/// An action that is bound to ClearIntent that clears the TextEditingController
/// passed to it.
class ClearAction extends Action<ClearIntent> {
ClearAction({required this.controller});
final TextEditingController controller;
@override
Object? invoke(covariant ClearIntent intent) {
controller.clear();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment