如何在Flutter中减小TextField文本输入框高度并去除多余内边距
问题根源
Flutter的TextField默认采用宽松布局规则,即使你设置了contentPadding: EdgeInsets.all(0),只要没有开启紧凑模式开关,仍然会保留上下默认留白,同时未指定行高的字体、占位的计数器组件也会占用额外空间,导致你无法缩小输入框高度。
解决方案
按以下步骤修改代码即可实现完全贴合设计的紧凑布局:
- 在
InputDecoration中添加isDense: true,这是启用输入框紧凑布局的核心开关 - 替换
counter: Text("")为counterText: "",彻底隐藏字符计数器避免占用额外空间 - 在文本样式中添加
height: 1.0,消除字体自带的上下行高偏移 - 给
TextField添加textAlignVertical: TextAlignVertical.center调整文本垂直位置,也可以根据设计需求设为TextAlignVertical.top - 按需调整
contentPadding的垂直数值,精准控制文本上下的留白
修改后完整代码
import 'package:flutter/material.dart'; import 'package:google_fonts/google_fonts.dart'; class CardHolderTextField extends StatelessWidget { const CardHolderTextField({ Key? key, }) : super(key: key); @override Widget build(BuildContext context) { return Container( width: 175, height: 40, // 可自由设置为需要的高度不会溢出 child: TextField( keyboardType: TextInputType.name, maxLength: 30, minLines: 1, textAlignVertical: TextAlignVertical.center, // 控制文本垂直对齐 textCapitalization: TextCapitalization.characters, style: GoogleFonts.mavenPro( fontSize: 10, height: 1.0, // 消除字体默认行高留白 color: Colors.white, textBaseline: TextBaseline.alphabetic, ), decoration: InputDecoration( isDense: true, // 启用紧凑布局 contentPadding: EdgeInsets.symmetric(vertical: 6, horizontal: 0), // 按需调整垂直padding counterText: "", // 彻底隐藏计数器 enabledBorder: UnderlineInputBorder( borderSide: BorderSide( color: Colors.white, ), ), disabledBorder: UnderlineInputBorder( borderSide: BorderSide( color: Colors.white, ), ), border: UnderlineInputBorder( borderSide: BorderSide( color: Colors.white, ), ), focusedBorder: UnderlineInputBorder( borderSide: BorderSide( color: Colors.white, ), ), fillColor: Colors.white, focusColor: Colors.white, ), ), ); } }
修改后你可以自由调整Container的高度到设计要求的数值,不会出现溢出问题,文本上下的多余空白也会完全消除,对齐Figma设计效果。
内容的提问来源于stack exchange,提问作者Raghav Joshi
相关产品推荐
相关产品推荐

