Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const KEYCODE_A = 0;
- const KEYCODE_HOME = 115;
- const KEYCODE_DEL = 117;
- const KEYCODE_END = 119;
- const KEYCODE_LEFT = 123;
- const KEYCODE_RIGHT = 124;
- class TextEditingRawKeyboardListener extends StatelessWidget {
- final Widget child;
- final FocusNode focusNode;
- final TextEditingController controller;
- TextEditingRawKeyboardListener({Key key, this.child, this.focusNode, this.controller}): super(key: key);
- @override
- Widget build(BuildContext context) => RawKeyboardListener(
- child: child,
- focusNode: focusNode,
- onKey: onKeyEvent
- );
- void onKeyEvent(RawKeyEvent e) {
- if (e.runtimeType != RawKeyDownEvent || e.data.runtimeType != RawKeyEventDataAndroid)
- return;
- final keyEvent = e.data as RawKeyEventDataAndroid;
- if (keyEvent.isModifierPressed(ModifierKey.metaModifier)) {
- if (keyEvent.keyCode == KEYCODE_A)
- controller.selection = TextSelection(baseOffset: 0, extentOffset: controller.text.length);
- }
- else if (keyEvent.isModifierPressed(ModifierKey.shiftModifier)) {
- if (keyEvent.keyCode == KEYCODE_LEFT)
- controller.selection = controller.selection.copyWith(extentOffset: max(controller.selection.extentOffset - 1, 0));
- else if (keyEvent.keyCode == KEYCODE_RIGHT)
- controller.selection = controller.selection.copyWith(extentOffset: min(controller.selection.extentOffset + 1, controller.text.length));
- else if (keyEvent.keyCode == KEYCODE_HOME)
- controller.selection = controller.selection.copyWith(extentOffset: 0);
- else if (keyEvent.keyCode == KEYCODE_END)
- controller.selection = controller.selection.copyWith(extentOffset: controller.text.length);
- }
- else if (keyEvent.keyCode == KEYCODE_HOME)
- controller.selection = TextSelection.collapsed(offset: 0);
- else if (keyEvent.keyCode == KEYCODE_END)
- controller.selection = TextSelection.collapsed(offset: controller.text.length);
- else if (keyEvent.keyCode == KEYCODE_DEL) {
- final start = min(controller.selection.baseOffset, controller.selection.extentOffset);
- var end = max(controller.selection.baseOffset, controller.selection.extentOffset);
- if (start == end && end < controller.text.length) {
- // If nothing is selected, behave as if the character after the cursor was selected (only for DEL).
- end += 1;
- }
- controller.text = controller.text.substring(0, start)
- + controller.text.substring(end);
- controller.selection = TextSelection.collapsed(offset: start);
- }
- }
- }
Add Comment
Please, Sign In to add comment