Flutter中调整TextField光标高度后下移,如何将光标垂直居中或添加底部内边距
Flutter TextField自定义光标高度偏移修正方案

该需求可直接通过Flutter内置参数实现,出现偏移的核心原因是你设置的cursorHeight远大于文本字号,且输入区上下内边距为0,没有足够的对称垂直空间承载光标,可通过以下两种方案修复:
方案1:使用
cursorOffset直接调整光标位置(无需修改其他配置)
Flutter 2.5及以上版本支持cursorOffset参数,传入负的Y轴偏移量即可将光标向上挪动,数值可根据实际显示效果微调:
只需在TextField配置中新增如下属性即可:cursorOffset: Offset(0, -6), // 数值越大光标上移距离越多方案2:匹配文本行高与输入区内边距,实现光标自然居中
调整文本行高与光标高度对齐,同时给输入区添加上下对称的内边距,让文本和光标都在输入区内垂直居中:- 给文本样式新增
height属性,让行高与光标高度匹配:
style: TextStyle(color: Colors.white, fontSize: 14, height: 2.2), // 30/14≈2.14,可根据效果微调- 修改输入区内边距,添加上下对称的垂直间距:
contentPadding: EdgeInsets.symmetric(vertical: 10, horizontal: 10),- 给文本样式新增
修复后完整代码示例
TextField( cursorHeight: 30, cursorColor: Colors.yellow, cursorWidth: 2, cursorRadius: Radius.circular(500), // 方案1新增的参数,若用方案2可删除该行 cursorOffset: Offset(0, -6), style: TextStyle(color: Colors.white, fontSize: 14, height: 2.2), obscureText: isPasswordTextField ? showPassword : false, decoration: InputDecoration( enabledBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.transparent), borderRadius: BorderRadius.all(Radius.circular(8)), ), focusedBorder: OutlineInputBorder( borderSide: BorderSide(width: 2, color: Colors.yellow), borderRadius: BorderRadius.circular(10), ), suffixIcon: isPasswordTextField ? IconButton( onPressed: () { setState(() { showPassword = !showPassword; }); }, icon: Icon( Icons.remove_red_eye, color: Colors.yellow, ), ) : null, contentPadding: EdgeInsets.symmetric(vertical: 10, horizontal: 10), filled: true, fillColor: Color.fromRGBO(28, 28, 28, 1), labelText: labelText, labelStyle: TextStyle( color: Colors.yellow, fontSize: 22, fontFamily: 'Exo', fontWeight: FontWeight.bold ), floatingLabelBehavior: FloatingLabelBehavior.always, hoverColor: Color.fromRGBO(54, 54, 54, 1), hintText: placeholder, hintStyle: TextStyle( fontSize: 14, color: Colors.white, ) ), )
内容的提问来源于stack exchange,提问作者Iliya Mansouri
相关产品推荐
相关产品推荐

