Flutter中如何让自定义textWidget内的文本居中显示?
解决TextField自定义组件label文本不居中的问题
你的问题出在两个核心点:
- 传入的
TextAlign.center参数没有在组件中实际生效 TextField的textAlign仅控制输入文本的对齐,label文本的对齐需要在InputDecoration的labelStyle中单独配置
修改后的自定义组件代码如下:
TextField textWidget(String text, IconData icon, bool isPasswordType, TextEditingController controller, TextAlign align) { return TextField( controller: controller, obscureText: isPasswordType, enableSuggestions: !isPasswordType, autocorrect: !isPasswordType, cursorColor: Colors.white, // 配置输入文本的对齐方式 textAlign: align, style: TextStyle(color: Colors.white.withOpacity(0.9)), decoration: InputDecoration( prefixIcon: Icon( icon, color: Colors.white70, ), labelText: text, // 在labelStyle中添加textAlign,控制label文本的对齐 labelStyle: TextStyle( color: Colors.white.withOpacity(0.9), textAlign: align, ), filled: true, floatingLabelBehavior: FloatingLabelBehavior.never, fillColor: const Color.fromARGB(255, 209, 107, 107).withOpacity(0.7), border: OutlineInputBorder( borderRadius: BorderRadius.circular(30.0), borderSide: const BorderSide(width: 0, style: BorderStyle.none)), ), keyboardType: isPasswordType ? TextInputType.visiblePassword : TextInputType.emailAddress, ); }
如果需要输入框获得焦点后,浮动状态的label也保持居中,可以在InputDecoration中额外添加alignLabelWithHint: true,让浮动label和输入文本的对齐方式保持一致。
内容的提问来源于stack exchange,提问作者ckot
相关产品推荐
相关产品推荐

