Flutter中如何实现输入文本框的动态居中对齐?
问题解决:TextFormField金额输入动态居中(仿Google Pay效果)
问题分析
你当前的代码存在两个核心问题导致无法实现动态居中:
- 用
Row拆分了货币符号和输入框,还给符号加了固定的left:82边距,导致输入文本只能在右侧Expanded区域内对齐,无法整体居中 - 未给
TextFormField设置textAlign: TextAlign.center,输入内容本身不会居中对齐
解决方案
下面提供两种实现方式,都能实现类似Google Pay的动态居中效果:
方式一:使用Stack整合符号与输入框
Center( child: Container( height: 124, width: 224, decoration: BoxDecoration( borderRadius: BorderRadius.circular(4), border: Border.all( color: formInputFieldBortderColor, width: 1, ), ), child: Center( child: Stack( alignment: Alignment.centerLeft, children: [ SizedBox( width: double.infinity, child: TextFormField( textDirection: TextDirection.ltr, textAlignVertical: TextAlignVertical.center, textAlign: TextAlign.center, // 核心:设置文本居中 maxLength: 3, controller: _textControllor, cursorColor: individualDateColor, keyboardType: TextInputType.number, inputFormatters: [ FilteringTextInputFormatter.digitsOnly ], style: GoogleFonts.mulish( color: activeTextColor, fontSize: 44, fontWeight: FontWeight.w400, letterSpacing: 2, ), decoration: const InputDecoration( hintText: "0", hintStyle: TextStyle(color: textLightColor), border: InputBorder.none, counterText: "", contentPadding: EdgeInsets.symmetric(horizontal: 40), // 给符号预留左侧空间 ), ), ), // 货币符号与输入文本同步居中 SvgPicture.asset(AssetRewards.rupees), ], ), ), ), )
方式二:利用TextFormField的prefixIcon属性
Center( child: Container( height: 124, width: 224, decoration: BoxDecoration( borderRadius: BorderRadius.circular(4), border: Border.all( color: formInputFieldBortderColor, width: 1, ), ), child: TextFormField( textDirection: TextDirection.ltr, textAlignVertical: TextAlignVertical.center, textAlign: TextAlign.center, // 核心:设置文本居中 maxLength: 3, controller: _textControllor, cursorColor: individualDateColor, keyboardType: TextInputType.number, inputFormatters: [ FilteringTextInputFormatter.digitsOnly ], style: GoogleFonts.mulish( color: activeTextColor, fontSize: 44, fontWeight: FontWeight.w400, letterSpacing: 2, ), decoration: InputDecoration( hintText: "0", hintStyle: TextStyle(color: textLightColor), border: InputBorder.none, counterText: "", // 自定义prefixIcon,去掉默认宽度限制 prefixIcon: Padding( padding: const EdgeInsets.only(right: 8), // 符号与文本的间距 child: SvgPicture.asset(AssetRewards.rupees), ), prefixIconConstraints: const BoxConstraints(minWidth: 0, minHeight: 0), ), ), ), )
修改说明
- 两种方式都添加了
textAlign: TextAlign.center,确保输入内容始终居中 - 移除了原代码中固定的边距和拆分的Row布局,让货币符号与输入文本作为一个整体动态居中
- 通过
contentPadding或prefixIconConstraints调整符号与文本的间距,避免重叠
内容的提问来源于stack exchange,提问作者Harshal Kothari
相关产品推荐
相关产品推荐

