我希望我的文本字段有一个清晰的按钮。我找到了如何使用装饰添加它的示例,但它的位置完全关闭。如何调整图标的位置?
此外,我无法使输入文本在输入字段中居中。我没有找到任何如何使输入框中的文本垂直居中的信息。
谢谢!
...
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',
),
)
);
}
最佳答案
要达到预期结果,需要进行三项更改:
- 使用
suffixIcon
代替suffix
- 删除垂直内容填充,例如
contentPadding: EdgeInsets.only(left:5)
当文本受到垂直约束时(例如容器高度为 30),垂直对齐文本。 - 删除
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',
),
)
);
最终结果:
关于Flutter TextField 清除按钮位置错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56977240/