I am trying to build logic based on detecting user keyboard events (e.g., when a user presses the backspace in a textfield). This seems to work on my builds for Android devices, but is not working for iOS devices. It seems as if the KeyboardListener that is wrapping my textfield is not being called when the user presses a key.
I have tried both the KeyboardListener and the RawKeyboardListener, and neither seem to work. How can I get this to work on iOS the same as it works for Android?
Here is a snippet of my code:
import 'package:flutter/material.dart'
class TestComponent extends StatelessWidget {
const TestComponent({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
child: KeyboardListener(
onKeyEvent: (key) {
print(key);
},
focusNode: FocusNode(),
child: TextField()),
);
}
}
I'm afraid the KeyboardListener
doesn't work for soft keyboards on iOS.
This is a known Flutter issue, here is the article that explains the problem in-depth: https://medium.com/super-declarative/why-you-cant-detect-a-delete-action-in-an-empty-flutter-text-field-3cf53e47b631
But if you need to track only "Backspace" key events and are willing to spend some time you can do a workaround:
I oversaw how the author solved that in this package: https://pub.dev/packages/pin_input_text_field
Basically, they have a hidden TextController
which contains the actual input text, and they have text fields visible to the user with a fake cursor with the animation that makes it blink like a real cursor.
They track the changes in the real text controller and update the fake text fields on the UI, based on the length of the text they animate the cursor on the corresponding input field.
This is how they simulate the behavior when you hit "Backspace" on the empty text field -> the focus switches to the previous text field.
If you open pin_input_text_field package the logic is located in _pin_state.dart
class.
Hope this helps