Flutter中TextField设置居中后文字轻微左上偏移如何解决?
修复方案
文字出现轻微左上偏移是因为Flutter TextField默认的装饰预留空间、字体行高、内置边距三个因素共同导致的,添加以下配置即可实现完全居中:
- 给
InputDecoration添加isDense: true,关闭默认的控件上下边距预留,同时显式禁用所有不需要的辅助元素(提示文本、计数文本等)的预留空间 - 给文本样式显式设置
height: 1.0,消除大字号字体默认的行高偏移 - 新增
StrutStyle配置,强制文字的上下基线对齐,避免字符绘制自带的偏移 - 统一不同交互状态下的边框配置,避免聚焦/失焦状态边框宽度不一致导致的位置偏移
修改后的完整代码如下:
import 'package:flutter/material.dart'; void main() => runApp(const Test()); class Test extends StatelessWidget { const Test({super.key}); @override Widget build(BuildContext context) { return MaterialApp( routes: { '/': (context) => const ExampleScreen(), }, ); } } class ExampleScreen extends StatelessWidget { const ExampleScreen({super.key}); @override Widget build(BuildContext context) { final textStyle = Theme.of(context).primaryTextTheme.headline2!.copyWith( color: Theme.of(context).colorScheme.onBackground, height: 1.0, // 显式设置行高为1,消除字体默认上下边距 ); return Scaffold( backgroundColor: Colors.grey[200], body: Center( child: Container( color: Colors.blue, width: 70, height: 70, child: Center( child: TextField( controller: TextEditingController.fromValue(TextEditingValue.empty.copyWith(text: '8')), autofocus: false, readOnly: true, // 不需要编辑可开启,避免光标偏移问题 style: textStyle, textAlign: TextAlign.center, textAlignVertical: TextAlignVertical.center, // 新增strut配置,强制文字基线对齐 strutStyle: StrutStyle( fontSize: textStyle.fontSize, height: textStyle.height, leading: 0, forceStrutHeight: true, ), decoration: InputDecoration( isDense: true, // 关闭默认控件边距 contentPadding: EdgeInsets.zero, // 禁用所有辅助元素的预留空间 counterText: '', helperText: '', prefixText: '', suffixText: '', // 统一所有状态的边框配置 enabledBorder: OutlineInputBorder( borderSide: BorderSide(color: Theme.of(context).disabledColor), borderRadius: BorderRadius.circular(8), ), focusedBorder: OutlineInputBorder( borderSide: BorderSide(color: Theme.of(context).disabledColor), borderRadius: BorderRadius.circular(8), ), border: OutlineInputBorder( borderSide: BorderSide(color: Theme.of(context).disabledColor), borderRadius: BorderRadius.circular(8), ), ), ), ), ), ), ); } }
内容的提问来源于stack exchange,提问作者Max Luchterhand
相关产品推荐
相关产品推荐

