【问题标题】:Flutter TextField clear button position wrongFlutter TextField清除按钮位置错误
【发布时间】:2019-11-20 11:12:12
【问题描述】:

我想为我的文本字段设置一个清除按钮。我找到了一个如何使用装饰添加它的示例,但它的位置完全关闭。如何调整图标的位置?

另外,我无法让输入文本在输入字段中居中。我没有找到任何如何将输入框中的文本垂直居中。

谢谢!

...
TextEditingController _textFieldController = TextEditingController();
...

Widget searchField(BuildContext context) {
  return Container(
    width: 200,
    height: 30,
    color: Colors.grey[250],
    child: TextField(
      controller: _textFieldController,
      decoration: InputDecoration(
        suffix: IconButton(
          padding: EdgeInsets.all(0),
          alignment: Alignment.bottomLeft,
          icon: Icon(Icons.cancel),
          onPressed: _onClear,
        ),
        border: OutlineInputBorder(),
        hintText: 'Blablabla',
      ),
    )
  );
}

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    将InputDecoration 的填充减少为零。

                 TextField(
                   decoration: InputDecoration(
                                  contentPadding: EdgeInsets.zero,
    

    【讨论】:

      【解决方案2】:

      要达到预期的结果,需要进行三个更改:

      1. 使用suffixIcon 而不是suffix
      2. 删除垂直内容填充,例如contentPadding: EdgeInsets.only(left:5) 在文本受到垂直约束时垂直对齐文本(例如容器高度为 30)。
      3. 删除IconButton 中的填充: padding: EdgeInsets.zero 以对齐图标。

      完整代码为:

      return Container(
        width: 200,
        height: 30,
        color: Colors.grey[250],
        child: TextField(
          controller: _textFieldController,
          decoration: InputDecoration(
            contentPadding: EdgeInsets.only(left: 5),
            suffixIcon: IconButton(
              padding: EdgeInsets.zero,
              icon: Icon(Icons.cancel),
              onPressed: () => print("clear"),
            ),
            border: OutlineInputBorder(),
            hintText: 'Blablabla',
          ),
        )
      );
      

      最终结果:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-09-19
        • 2011-06-26
        • 2023-03-19
        • 2019-11-25
        • 1970-01-01
        • 2016-03-15
        • 2020-02-01
        • 1970-01-01
        相关资源
        最近更新 更多