[英]How to make square raised buttons in Flutter?
我在一个 Wrap 中有一大堆RaisedButton
,这样它们就可以根据需要占用任意多的行。 但我确实想将按钮扩展为方形按钮。 我可以通过将Wrap
替换为GridView.count
并使用crossAxisCount
来做到这一点,但是当有更多可用空间时,按钮会变得不必要地大。 基本上,我希望它们都是相同大小的正方形,都只和它们所容纳的内容一样大。 它们不是动态加载或任何东西,所以不用担心性能问题。 但我们正在研究相当小的屏幕的可能性,因此滚动也需要成为可能。 有没有办法让所有这些事情都正确?
这是当前代码及其生成的内容:
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Wrap(
direction: Axis.horizontal,
children: <Widget>[
RaisedButton.icon(
onPressed: () {}
label: Text('Park In', style: TextStyle(fontSize: 15.0)),
icon: Icon(Icons.add),
),
RaisedButton.icon(
onPressed: () {}
label: Text('Park Out', style: TextStyle(fontSize: 15.0)),
icon: Icon(Icons.eject),
),
RaisedButton.icon(
onPressed: () {}
label: Text('Maintainence In', style: TextStyle(fontSize: 15.0)),
icon: Icon(Icons.vertical_align_bottom),
),
RaisedButton.icon(
onPressed: () {}
label: Text('Maintainence Out', style: TextStyle(fontSize: 15.0)),
icon: Icon(Icons.vertical_align_top),
),
RaisedButton.icon(
onPressed: null,
label: Text('Move', style: TextStyle(fontSize: 15.0)),
icon: Icon(Icons.open_with),
),
],
),
);
}
用 GridView 替换为 2 作为crossAxisCount
给出了这个,这非常接近我需要的(理想情况下文本会更大并且换行 - 如果没有给出正确的空间它似乎会溢出,但我想我可以处理这个问题事情就是这样):
但是当我将 go 设置为横向模式时,3 个按钮可以很容易地排成一排,GridView 就会“嗯,不管怎样”,并使按钮变得巨大:
您可以为此使用OrientationBuilder
。 它将为您处理方向变化:
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("word"),
),
body: OrientationBuilder(
builder: (context, orientation) {
int count = 2;
if(orientation == Orientation.landscape){
count = 3;
}
return GridView.count(
crossAxisCount: count,
children: <Widget>[
RaisedButton.icon(
onPressed: () {},
label: Text('Park In', style: TextStyle(fontSize: 15.0)),
icon: Icon(Icons.add),
),
RaisedButton.icon(
onPressed: () {},
label: Text('Park Out', style: TextStyle(fontSize: 15.0)),
icon: Icon(Icons.eject),
),
RaisedButton.icon(
onPressed: () {},
label:
Text('Maintainence In', style: TextStyle(fontSize: 15.0)),
icon: Icon(Icons.vertical_align_bottom),
),
RaisedButton.icon(
onPressed: () {},
label:
Text('Maintainence Out', style: TextStyle(fontSize: 15.0)),
icon: Icon(Icons.vertical_align_top),
),
RaisedButton.icon(
onPressed: null,
label: Text('Move', style: TextStyle(fontSize: 15.0)),
icon: Icon(Icons.open_with),
),
],
);
},
),
);
}
尝试AspectRatio
AspectRatio(
aspectRatio: 1,
child: RaisedButton(
onPressed: () {},
child: Text('hi'),
),
);
截至目前 flutter 3.3.10 不支持凸起按钮。 但是您可以使用其他按钮,例如 TextButton,为此您只需要将它包装在 AspectRatio 小部件中
就像前面的例子
AspectRatio(
aspectRatio: 1,
child: TextButton(
onPressed: () {},
child: Text('hi'),
),
);
不要将 AspectRatio 小部件放在无限高度或宽度小部件内,以避免呈现错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.