Flutter:为ButtonBar中两个按钮设置等宽及文本自适应动态高度
解决Flutter中两个按钮等宽且高度自适应的问题
我懂你想要的效果——就像Android里LinearLayout设置weight那样,让两个按钮平分水平空间,同时高度能跟着文本内容自动调整。原来的ButtonBar确实搞不定这个场景,它默认是让按钮按自身内容宽度布局,长文本按钮自然容易被截断。
这里有个简单靠谱的方案,用Row配合Expanded组件就能完美实现你要的LinearLayout权重效果:
import 'package:flutter/material.dart'; class NewScreen extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( automaticallyImplyLeading: true, title: Text("Building layouts"), leading: IconButton( icon: Icon(Icons.arrow_back), onPressed: () => Navigator.pop(context, false), )), body: myLayoutWidget(), ), ); } } Widget myLayoutWidget() { return Container( padding: EdgeInsets.symmetric(horizontal: 16.0), // 给左右加些边距,避免按钮贴屏幕边缘 child: Column( children: <Widget>[ Row( children: <Widget>[ Expanded( child: RaisedButton( onPressed: () {}, child: Text("Very long text button"), padding: EdgeInsets.symmetric(vertical: 8.0), // 可选:调整按钮内边距让文本显示更舒适 ), ), SizedBox(width: 12.0), // 给两个按钮之间留些间距,优化视觉体验 Expanded( child: RaisedButton( child: Text("Very very very very long text button"), color: Colors.red, onPressed: () {}, padding: EdgeInsets.symmetric(vertical: 8.0), ), ) ], ), ], ), ); }
这个方案的核心逻辑:
Expanded会强制子组件平分Row的可用水平空间,完全对应Android里layout_weight=1的效果,保证两个按钮宽度绝对相等。RaisedButton默认高度是wrap_content,会自动根据文本的行数调整自身高度,完美适配长文本不会被截断。- 加入
SizedBox是为了避免两个按钮挤在一起,你可以根据自己的设计需求调整间距的数值。
如果担心文本在按钮里还是放不下,还可以给Text组件加上softWrap: true(默认就是true,一般不用额外设置),或者maxLines: null允许文本无限换行,确保内容完整显示。
内容的提问来源于stack exchange,提问作者camelCaseCoder
相关产品推荐
相关产品推荐

