描述
Flutter中使用TextField输入框时,若是左右两边有图标的时候,经常会出现输入框内的文字和图标对不齐的情况。
-
提示内容和搜索图标没有对齐。
-
输入内容和图标没有对齐。
当搜索框高度有限时,这种对不齐的情况会更加明显。
- 源码。
child: Row(
children: [
Icon(
Icons.search,
color: Colors.grey,
size: 24.0,
),
Expanded(
child: TextField(
maxLines: 1,
decoration: InputDecoration(
hintText: "请输入搜索内容",
hintStyle: const TextStyle(color: Colors.grey, fontSize: 14),
border: InputBorder.none,
),
onChanged: (value) {
onChange(value);
},
onEditingComplete: () {
FocusScopeNode currentFocus = FocusScope.of(context);
/// 键盘是否是弹起状态,弹出且输入完成时收起键盘
if (!currentFocus.hasPrimaryFocus &&
currentFocus.focusedChild != null) {
FocusManager.instance.primaryFocus!.unfocus();
}
},
),
)
],
),
解决方案
- 将InputDecoration中isDense设置为true。
TextField(
maxLines: 1,
decoration: InputDecoration(
hintText: "请输入搜索内容",
hintStyle: const TextStyle(color: Colors.grey, fontSize: 16),
border: InputBorder.none,
isDense: true
),
),
此时文字和图标已居中对齐。
- 将InputDecoration中contentPadding设置为EdgeInsets.zero。
TextField(
maxLines: 1,
decoration: InputDecoration(
hintText: "请输入搜索内容",
hintStyle: const TextStyle(color: Colors.grey, fontSize: 16),
border: InputBorder.none,
contentPadding: EdgeInsets.zero,
isDense: true
)
此时去掉了原本默认的内边距,文字会向下对齐,以最底部的基准线对齐。相比于只将isDense设置为true,文字更靠下。
- TextField中文字样式中textBaseline设置为TextBaseline.alphabetic。
child: TextField(
maxLines: 1,
decoration: InputDecoration(
hintText: "请输入搜索内容",
hintStyle: const TextStyle(color: Colors.grey, fontSize: 16),
border: InputBorder.none,
contentPadding: EdgeInsets.zero,
isDense: true
),
style: TextStyle(
fontSize: 16.0,
color: Colors.grey,
textBaseline: TextBaseline.alphabetic
),
这个效果和将contentPadding设置为EdgeInsets.zero效果一样,用于文字对齐。