Flutter中TextField和图标对齐

描述

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();
              }
            },
          ),
        )
      ],
    ),

解决方案

  1. 将InputDecoration中isDense设置为true。
TextField(
            maxLines: 1,
            decoration: InputDecoration(
              hintText: "请输入搜索内容",
              hintStyle: const TextStyle(color: Colors.grey, fontSize: 16),
              border: InputBorder.none,
              isDense: true
            ),
          ),

此时文字和图标已居中对齐。
在这里插入图片描述

  1. 将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,文字更靠下。
在这里插入图片描述

  1. 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效果一样,用于文字对齐。
在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值