如何动态调整Row组件内按钮的文本大小以避免溢出?
解决多语言按钮文本溢出问题
问题分析
你当前代码仅给第二个按钮用了AutoSizeText,第一个按钮仍是普通Text,长文本语言下必然溢出;另外AutoSizeText需要明确的宽度约束才能触发字号调整,原代码未提供有效约束。
解决方案
- 两个按钮的文本统一改用
AutoSizeText - 用
Expanded包裹按钮分配Row空间,给AutoSizeText设置宽度约束 - 调整按钮内边距和最小尺寸,保证布局合理性
修改后的代码
return Dialog( backgroundColor: Colors.transparent, elevation: 0, child: InkWell( onTap: () { Navigator.of(context).pop(); }, child: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Container( width: kIsWeb ? 40.w : 100.w, color: Theme.of(context).dialogBackgroundColor, padding: EdgeInsets.all(15.sp), child: Column(children: <Widget>[ Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Expanded( flex: 1, child: OutlinedButton( style: OutlinedButton.styleFrom( shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20.0)), side: BorderSide(width: 2, color: Theme.of(context).primaryColor), primary: Colors.black54, padding: EdgeInsets.symmetric(horizontal: 8.sp), minimumSize: Size(0, 40.sp), ), onPressed: () { Navigator.of(context).pop(); }, child: AutoSizeText( AppLocalizations.of(context)!.joinGameDialogCancelButton, style: TextStyle(fontSize: kIsWeb ? 4.sp : 12.sp), overflow: TextOverflow.clip, stepGranularity: 1, maxLines: 1, minFontSize: 8.sp, maxWidth: double.infinity, ), ), ), SizedBox(width: 10.sp), Expanded( flex: 1, child: ElevatedButton( style: TextButton.styleFrom( shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20.0)), backgroundColor: Theme.of(context).primaryColor, primary: Colors.white, padding: EdgeInsets.symmetric(horizontal: 8.sp), minimumSize: Size(0, 40.sp), ), onPressed: () async { if (formKey.currentState!.validate()) { Navigator.of(context).pop(); widget.onFinished(nameController.text.trim()); } }, child: AutoSizeText( AppLocalizations.of(context)!.joinGameDialogJoinButton, style: TextStyle(fontSize: kIsWeb ? 4.sp : 14.sp), overflow: TextOverflow.clip, stepGranularity: 1, maxLines: 1, minFontSize: 8.sp, maxWidth: double.infinity, ), ), ), ], ), Padding(padding: EdgeInsets.only(top: 15.sp)), Text("some eula text"), ]), ) ], ), ), ), );
关键修改说明
- Expanded包裹按钮:让两个按钮平分Row可用空间,避免单个按钮被挤压
- 统一使用AutoSizeText:确保所有按钮文本都能根据空间自动调字号
- 设置minFontSize:防止字体缩至无法阅读的大小
- 调整按钮padding和minimumSize:保证按钮有足够点击区域和美观形态
- 添加按钮间距:避免按钮紧挨,提升视觉体验
内容的提问来源于stack exchange,提问作者progNewbie
相关产品推荐
相关产品推荐

