乐闻世界logo
搜索文章和话题

How to set the width and height of a button in Flutter?

1个答案

1

In Flutter, setting the width and height of a button can be achieved through various methods, primarily depending on the button type and layout requirements. Here are some common approaches:

Using SizedBox to Wrap Buttons

Using SizedBox to constrain the button's width and height is the most straightforward approach. For example, if you want to set an ElevatedButton to have a width of 150 pixels and a height of 50 pixels, you can do the following:

dart
SizedBox( width: 150.0, height: 50.0, child: ElevatedButton( onPressed: () {}, child: Text('Click me'), ), );

Using ButtonStyle's minimumSize

Starting from Flutter 2.0, ElevatedButton, TextButton, and OutlinedButton all support ButtonStyle. You can set the button's minimum width and height using ButtonStyle. For example:

dart
ElevatedButton( style: ButtonStyle( minimumSize: MaterialStateProperty.all(Size(150.0, 50.0)), ), onPressed: () {}, child: Text('Click me'), );

Using Container to Wrap Buttons

Similar to using SizedBox, you can also use Container to set the dimensions, which is particularly useful when you need to add additional styles (such as decorations):

dart
Container( width: 150.0, height: 50.0, child: ElevatedButton( onPressed: () {}, child: Text('Click me'), ), );

Using Layout Constraints

In more complex layouts, you might need to dynamically adjust the button's size based on other parts of the layout. You can use widgets like Flex, Expanded, or Flexible for this purpose. For example, making the button fill all available space in a Row:

dart
Row( children: <Widget>[ Expanded( child: ElevatedButton( onPressed: () {}, child: Text('Click me'), ), ), ], );

These are several common methods for setting the width and height of buttons in Flutter.

2024年7月1日 12:16 回复

你的答案