dart 没有输入时,Flutter TextField光标未垂直居中

blmhpbnm  于 2023-03-27  发布在  Flutter
关注(0)|答案(3)|浏览(411)

我设置了flutter的TextFieldcursorHeight属性,但是当TextField中有没有内容时,光标无法以hintText为垂直居中,如下图所示:

但是,当TextField中有为内容时,内容文本和光标将垂直居中,如下图所示:

这是我的代码:

TextField(
  decoration: const InputDecoration(
    hintText: "Type here to add a quick TODO...",
    enabledBorder: InputBorder.none,
    focusedBorder: InputBorder.none,
    contentPadding: EdgeInsets.all(0),
  ),
  cursorHeight: 25,
  cursorRadius: Radius.circular(10),
  maxLines: 1,
  style: TextStyle(
    fontSize: 15,
  ),
  onChanged: (value) {
    setState(() {
      _typedContent = value;
    });
  },

有没有什么方法可以使光标垂直居中,即使没有文本输入?

nx7onnlm

nx7onnlm1#

自定义文本高度(height property

TextField(
    style: TextStyle(
      height: 1.5
    ),
  ),
dy1byipe

dy1byipe2#

首先,如果cursorHeight属性不是必须的,可以删除它。
第二个选择是使用TextStyle的height属性。据我所知,你可以从以下比例开始尝试:cursorHeight/textSize。无论如何,我建议您阅读有关height property of TextStyle.的内容

style: TextStyle(
          fontSize: 15,
          height: 25/15
        ),
tyu7yeag

tyu7yeag3#

我也在努力解决这个问题,但我找到了一个简单的解决方案。光标垂直对齐与几件事有关。
1.光标高度
1.文字高度
1.文本字体大小
通过设置(3)fontSize,光标向上增长,而通过设置(1)cursorHeight,光标向下增长。要注意到这一点,并能够正确调整到hintText垂直居中的光标,您需要:首先设置(2)文本高度为1。然后向上和向下增加光标,直到你满意它与提示文本居中的外观。
下面是一个例子:

TextField(
      decoration: InputDecoration(
        hintText: 'Search',
        hintStyle: TextStyle(
          fontSize: 19,
        ),
      ),
      cursorHeight: 17,
      style: TextStyle(
        height: 1,
        fontSize: 21,
      ),
    );

结果是:Center Cursor with Search hint text

相关问题