gpt4 book ai didi

flutter - 如何在不显示键盘的情况下聚焦 TextField?

转载 作者:行者123 更新时间:2023-12-03 03:04:49 24 4
gpt4 key购买 nike

我需要专注于 TextField 但不显示键盘。
如果用户点击 TextField,则键盘只需要显示

我尝试了 2 种方法。

第一次尝试:

这样键盘就会显示出来,并且在屏幕构建后隐藏起来,这不太好看。

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
),

并且在 build() 之外:

void _onAfterBuild(BuildContext context) {
SystemChannels.textInput.invokeMethod('TextInput.hide');
}

第二次尝试:

通过这种方式,键盘隐藏在较低的级别,并且更好看。问题是 onTap 永远不会被调用,所以键盘永远不会显示,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 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

最佳答案

text_input.dart 有一个方法

    void show({bool ifShowKeyBoard = true}) {
assert(attached);
if (ifShowKeyBoard) {
TextInput._instance._show();
}
}
我改变了这个方法,它有效

关于flutter - 如何在不显示键盘的情况下聚焦 TextField?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59073789/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com