首页 > 解决方案 > 按下按钮时,如何保持 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 在按下时不会聚焦文本字段?

标签: flutterdartflutter-layout

解决方案


我只能想到 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 来实现。


推荐阅读