Reputation: 660
I set the cursorHeight
property of flutter's TextField
, but when there is no content in the TextField
, the cursor cannot be vertically centered with the hintText
, as shown in the following figure:
However, when there is content in the TextField
, the content text and the cursor will be vertically centered, as shown in the following figure:
This is my code:
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;
});
},
Is there any way to make the cursor center vertically even when there is no text input?
Upvotes: 3
Views: 6519
Reputation: 1
I had the same problem. I addressed it by setting
textAlignVertical: TextAlignVertical.top,
and now it seems the cursor is vertically centered.
If you've already adjusted things like font size but still want to display the cursor at the top, this might solve the issue.
Upvotes: 0
Reputation: 1144
You can try to add the following properties to your text field:
1- textAlignVertical: TextAlignVertical.center
2- In InputDecoration add contentPadding: EdgeInsets.only(top: 0)
3- In IconButton add padding: EdgeInsets.only(top: 0)
TextField(
textAlignVertical: TextAlignVertical.center,
decoration: InputDecoration(
contentPadding: EdgeInsets.only(top: 0),
prefixIcon: Icon(
Icons.search,
),
hintStyle: TextStyle(
fontSize: 20,
),
suffixIcon: IconButton(
padding: EdgeInsets.only(top: 0),
icon: Icon(Icons.cancel),
onPressed: null,
),
hintText: "Search"
)
)
Upvotes: 1
Reputation: 51
I also struggled with this but i found an easy solution. NOTE: The Cursor vertical alignment is related to a few things.
The cursor grow upward by setting the (3) fontSize while it grows downward by setting the (1) cursorHeight. To notice this and be able to adjust properly to vertically center the cursor with the hintText you need to: First set (2) the Text height to 1. Second grow the cursor both upward and downward until u are satisfied with how it looks centered with the hinttext.
Here is an example:
TextField(
decoration: InputDecoration(
hintText: 'Search',
hintStyle: TextStyle(
fontSize: 19,
),
),
cursorHeight: 17,
style: TextStyle(
height: 1,
fontSize: 21,
),
);
And the result: Center Cursor with Search hint text
Upvotes: 1
Reputation: 774
Firstly you can remove the cursorHeight
property if it is not a must.
Second option is using the height
property of your TextStyle. As far as I remember you can start trying with following ratio: cursorHeight/textSize. In any case I recommend you reading about height property of TextStyle.
style: TextStyle(
fontSize: 15,
height: 25/15
),
Upvotes: 5
Reputation: 3488
TextField(
style: TextStyle(
height: 1.5
),
),
Upvotes: 2