flutter - 按下按钮时,如何保持 TextField 内的 IconButton 不聚焦文本字段?
问题描述
这是我的脚手架内文本字段的代码:
child: TextField(
obscureText: _obscureText,
controller: myController2,
focusNode: myFocusNode2,
textInputAction: TextInputAction.done,
onSubmitted: (value){
myFocusNode2.unfocus();
_loginMethod();
},
decoration: InputDecoration(
labelText: "Password",
border: OutlineInputBorder(),
suffixIcon: IconButton(
icon: Icon(_obscureText ? Icons.visibility_off: Icons.visibility),
onPressed: (){
setState(() {
_obscureText = !_obscureText;
});
Timer.run(() => myFocusNode2.unfocus());
},
)
),
),
我现在拥有的东西可以工作,但它根本不干净。大多数情况下,文本字段会聚焦一秒钟,然后 .unfocus() 会在延迟后将其取消聚焦,所以我得到了这种跳跃效果,键盘弹出然后返回。只有几次文本字段永远不会集中,我不明白为什么。
有没有办法确保 IconButton 在按下时不会聚焦文本字段?
解决方案
我只能想到 3 个解决方案,不是完美的,但只是完成工作
1-将focusNode与计时器一起使用
将 foucsNode 链接到文本文件后,按钮功能可能是这样的
onPressed: () {
Timer.periodic(Duration(microseconds: 1), (_) {
focusNode.unfocus();
});
//Write your code here
},
2-使用堆栈
Stack(
alignment: Alignment.centerRight,
children: <Widget>[
TextField(
decoration: InputDecoration(
labelText: "Password",
border: OutlineInputBorder(),
),
),
IconButton(
icon: Icon(Icons.ac_unit),
onPressed: () {
//do any thing
},
),
],
),
3-正如 Afridi Kayal 所说,您可以使用一行
Row(
children: <Widget>[
Expanded(
child: TextField(
focusNode: focusNode,
enabled: enabled,
autofocus: false,
textInputAction: TextInputAction.done,
decoration: InputDecoration(
labelText: "Password",
border: OutlineInputBorder(),
),
),
),
IconButton(
icon: Icon(Icons.visibility),
onPressed: () {
print('object');
},
),
],
),
如果您最终选择数字 2 或 3,并且您希望在关注文本文件时更改按钮颜色,您也可以使用 focusNode 来实现。
推荐阅读
- python - 仅当我按住开火键时,弹丸才会移动
- python - 使用 Python 在 Chrome Selenium 中激活 Flash
- terraform - Terraform - 在变量默认值中使用数据源输出
- qlikview - QlikView 中的饼图
- ruby-on-rails - Rails API 子集响应
- javascript - jQuery文件中的toggleClass和执行顺序
- javascript - 如何删除选定的输入值
- gradle - 在进行 Gradle Clean 构建时在 Spring Boot 应用程序中收到警告
- android - 如何使用 pybluez 构建 Android 蓝牙服务器应用程序处理从 Raspberry Pi 发送的数据
- node.js - npm 安装权限被拒绝 (macOS)