I need to focus on a TextField but without showing the keyboard. The keyboard needs to be shown only if the user taps on the TextField.
I tried 2 ways.
First attempt:
This way the keyboard shows and it's hidden after screen build which is not nice to see.
Builder:
TextFormField(
controller: barcodeStringController,
focusNode: myFocusNode,
autofocus: true,
textAlign: TextAlign.right,
textInputAction: TextInputAction.done,
textCapitalization: TextCapitalization.characters,
style: TextStyle(fontSize: 20),
maxLines: null,
onTap: () {
SystemChannels.textInput.invokeMethod('TextInput.show');
},
//... Other event listeners to handle submit
),
And out of build():
void _onAfterBuild(BuildContext context) {
SystemChannels.textInput.invokeMethod('TextInput.hide');
}
Second attempt:
This way the keyboard is hidden at a lower level and it's nicer to see. The problem is that onTap is never called so the keyboard never shows, neither onTap.
Builder:
GestureDetector(
onTap: () {
SystemChannels.textInput.invokeMethod('TextInput.show');
},
child: TapOnlyFocusTextField(
controller: barcodeStringController,
focusNode: myFocusNode, //this is a TapOnlyFocusTextFieldFocusNode
textAlign: TextAlign.right,
textInputAction: TextInputAction.done,
textCapitalization: TextCapitalization.characters,
style: TextStyle(fontSize: 20),
cursorColor: Colors.black,
//... Other event listeners to handle submit
),
),
TapOnlyFocusTextField Class:
class TapOnlyFocusTextField extends EditableText {
TapOnlyFocusTextField({
@required TextEditingController controller,
@required TextStyle style,
@required Color cursorColor,
bool autofocus = false,
Color selectionColor,
FocusNode focusNode,
TextAlign textAlign,
TextInputAction textInputAction,
TextCapitalization textCapitalization,
onSubmitted,
onChanged,
}) : super(
controller: controller,
focusNode: focusNode,
style: style,
cursorColor: cursorColor,
autofocus: autofocus,
selectionColor: selectionColor,
textAlign: textAlign,
textInputAction: textInputAction,
textCapitalization: textCapitalization,
maxLines: null,
onSubmitted: onSubmitted,
backgroundCursorColor: Colors.black,
onChanged: onChanged,
);
@override
EditableTextState createState() {
return TapOnlyFocusTextFieldState();
}
}
class TapOnlyFocusTextFieldState extends EditableTextState {
@override
void requestKeyboard() {
super.requestKeyboard();
//hide keyboard
SystemChannels.textInput.invokeMethod('TextInput.hide');
}
}
TapOnlyFocusTextFieldFocusNode Class:
class TapOnlyFocusTextFieldFocusNode extends FocusNode {
@override
bool consumeKeyboardToken() {
// prevents keyboard from showing on first focus
return false;
}
}
I know that there's already an open issue in Flutter Github about this but I need to find a solution: https://github.com/flutter/flutter/issues/16863