flutter textfield设置高度后内容区无法居中?

textfiled 设置高度后,内容永远无法居中,最后找到原因

  1. decoration: 中有一个 contentPadding属性,设置这个属性对应的Padding值即可

2.设置对其方式textBaseline

child: TextField(
    style: TextStyle(textBaseline: TextBaseline.alphabetic),
)

如果需要全局配置 可以使用下面方式
ThemeData(
    textTheme: TextTheme(subhead: TextStyle(textBaseline: TextBaseline.alphabetic)),

如果设置了上面这种方法仍然不能解决居中问题,可以试试下面👇这种方式
在使用TextField的时候如果设置了textField高度,容易导致内容无法居中的问题,刚开始使用的contentPadding,设置内容上下便宜的padding来控制内容居中,这种方式能达到效果,但是在部分小屏手机上还是会出现不居中的情况,如图所示

安卓的机型更多,如果都要做适配,那将是及其困难的事情

在网上也看了一些其他的解决方案
https://github.com/flutter/flutter/issues/40248
通过设置 textBaseline: TextBaseline.alphabetic 来实现内容居中,设置了一番 发现并没有达到理想的效果

这里推荐一种确实有效的方法,来解决TextField内容居中的问题
我们通常在使用textField的时候默认将其border设置为 InputBorder.none,如果我们给textField设置外边框,你会发现,内容竟然居中了

由此可见,当我们给textField设置了外边框,textField的内容就会居中显示,那么剩下的问题就简单了,将外边框设置为透明色即可

            border: OutlineInputBorder(
                      borderSide: BorderSide(
                        color: Colors.transparent,
                      ),
                    ),
                    enabledBorder: OutlineInputBorder(
                      borderSide: BorderSide(
                        color: Colors.transparent,
                      ),
                    ),
                    disabledBorder: OutlineInputBorder(
                      borderSide: BorderSide(
                        color: Colors.transparent,
                      ),
                    ),
                    focusedBorder: OutlineInputBorder(
                      borderSide: BorderSide(
                        color: Colors.transparent,
                      ),
                    ),

有一点很重要 contentPadding一定要设置上下边距为0

contentPadding: EdgeInsets.only(top: 0, bottom: 0)

以上就是能够确保textField内容能够完美居中的解决方案

1.设置textField有边框,并设置外边框为透明色
2.设置contentPadding:EdgeInsets.only(top: 0, bottom: 0)
posted @ 2019-10-15 11:38  qqcc1388  阅读(6376)  评论(0编辑  收藏  举报