【发布时间】:2022-11-14 04:31:11
【问题描述】:
目标:按下发送按钮时,不要关闭键盘并保持打开/聚焦 问题:按下发送按钮时,键盘关闭,然后由于focusNode.requestFocus重新打开,之后按下发送按钮时,键盘不再打开 寻找两个选项:
- (理想)按下发送按钮时不要让键盘关闭
- (okay) 无论发送按钮关闭多少次都打开键盘
这是示例用户界面:
return Form( key: _formKey, child: Row( children: <Widget>[ Expanded( child: TextFormField( focusNode: chatController.focusNode, // textInputAction: TextInputAction.none, // didn't help // onEditingComplete: () {}, // didn't help ) ), IconButton( icon: const Icon(Icons.send), onPressed: () async { SystemChannels.textInput .invokeMethod('TextInput.hide'); if (_formKey.currentState!.validate()) { await chatController.sendMessage(context); } } ), ], ) );这是控制器:
late FocusNode focusNode; @override void onReady() async { // tried onInit as well focusNode = FocusNode(); super.onReady(); } void sendMessage(BuildContext context) async { // focusNode.unfocus(); // didn't help // focusNode2.requestFocus(); // tried to give focus to another widget and take it back, but didn't help final a1 = focusNode.hasFocus; // except the very first call, this is true even when focusNode.unfocus() is called // neither of these work the second time focusNode.requestFocus(); // FocusScope.of(context).requestFocus(focusNode); }我能够跟踪代码,并且当第二次呼叫到达焦点管理器here 时,此条件始终为真:
if (hasPrimaryFocus && (_manager!._markedForFocus == null || _manager!._markedForFocus == this)) {即使键盘已关闭,它也会返回而不会再次尝试打开键盘
【问题讨论】:
-
你为什么在发送回调中调用
SystemChannels.textInput.invokeMethod('TextInput.hide');? -
@voidvoid 我觉得很愚蠢,这就是问题所在,我从示例项目中复制了这段代码,但从未注意过,谢谢
-
很高兴我能帮上忙,我认为这不是唯一的问题。每个人有时都会犯愚蠢的错误:))