我需要专注于一个文本字段,但不显示键盘。如果用户点击文本字段,则需要仅显示键盘。
我试了两种方法。
第一次尝试:
这样的键盘显示和它的屏幕构建后,这是不好看隐藏。
建设者:
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
),
在build()之外:
void _onAfterBuild(BuildContext context) {
SystemChannels.textInput.invokeMethod('TextInput.hide');
}
第二次尝试:
这样键盘就隐藏在较低的位置,看起来更好。问题是onTap从未被调用,所以键盘永远不会显示,onTap也不会。
建设者:
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 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 TapOnlyFocusTextFieldFocusNode extends FocusNode {
@override
bool consumeKeyboardToken() {
// prevents keyboard from showing on first focus
return false;
}
}
我知道在Flutter Github上已经有一个公开的问题,但我需要找到一个解决方案:https://github.com/flutter/flutter/issues/16863
3条答案
按热度按时间deikduxw1#
text_input. dart有一个方法
我把方法改了一下,这样就行了
dgenwo3n2#
如图所示:https://stackoverflow.com/a/60392327/4693979
但我更喜欢在initState中这样做:
别忘了将自动对焦设置为true。
oxiaedzo3#
如何在不显示键盘的情况下关注TextField
您可以创建自己的
UIViewRepresentable
并更改UITextField
的inputView
。下面的
XTextField
只会在按住焦点后点击时显示键盘。根据您的喜好定制。