gpt4 book ai didi

dart - 如何防止键盘在 flutter 中按下提交键时消失?

转载 作者:IT王子 更新时间:2023-10-29 07:11:49 25 4
gpt4 key购买 nike

我正在制作一个 flutter 应用程序,用户可以在其中键入消息并点击键盘中的发送按钮来发送消息。问题是当我按下发送按钮时,消息被发送但键盘自动消失。我怎样才能防止这种情况发生?提前致谢。

TextField(
autofocus: true,
keyboardType: TextInputType.multiline,
maxLines: null,
decoration: new InputDecoration.collapsed(
hintText: "Let's talk",
border: UnderlineInputBorder(
borderRadius: BorderRadius.circular(1),
),
),
textInputAction: TextInputAction.send,
onSubmitted: null,
)

最佳答案

TextField 小部件有一个参数就是为了这个目的!

虽然 onSubmit 回调可用于在用户按下完成时处理业务逻辑,但还有一个名为 onEditingComplete 的属性,专门用于处理与焦点相关的逻辑。因此,您应该同时使用两者,以获得更好的代码可读性。

根据docs :

The default implementation of onEditingComplete executes 2 differentbehaviors based on the situation:

When a completion action is pressed, such as "done", "go", "send", or"search", the user's content is submitted to the controller and thenfocus is given up.

When a non-completion action is pressed, such as "next" or "previous",the user's content is submitted to the controller, but focus is notgiven up because developers may want to immediately move focus toanother input widget within onSubmitted.

因此,如果您不喜欢这种行为,例如,“发送”在这里被视为“完成操作”,因此在即时消息(聊天)应用程序中,每次用户发送一条短消息时,键盘都会崩溃。但是,如果我们将 onEditingComplete 回调重写为一个空函数,它将停止默认行为并且不会隐藏键盘。

示例代码:

TextField(
controller: _controller,
onSubmitted: (value) {
sendMessage(text);
_controller.clear();
},
onEditingComplete: () {}, // this prevents keyboard from closing
textInputAction: TextInputAction.send,
)

演示:

demo gif

有关 onSubmittedonEditingComplete 回调的完整解释和比较,请查看 my other answer here .

关于dart - 如何防止键盘在 flutter 中按下提交键时消失?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55863766/

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