有很多方法可以制作全宽度按钮。但我认为你应该了解在不同场景下制作全宽度小部件的概念:
当你使用嵌套小部件时,很难确定父小部件的宽度。在嵌套小部件中无法指定宽度。因此,您应该使用 Expanded 或 Column 与 CrossAxisAlignment 设置为 Stretch。
在其他情况下,可以使用媒体查询宽度或 double.infinity。
以下是一些嵌套小部件和单个小部件的示例:
第一个示例:
Expanded(
child: MaterialButton(
onPressed: () {},
child: const Text("Button Text"),
color: Colors.indigo,
textColor: Colors.white,
)
)
第二点:
Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
MaterialButton(
onPressed: () {},
child: const Text("Button Text"),
color: Colors.indigo,
textColor: Colors.white,
)
]
)
第三步:
ButtonTheme( // if use media query, then will not work for nested widgets.
minWidth: double.infinity, //Or use 'width: MediaQuery.of(context).size.width'
child: MaterialButton(
onPressed: () {},
child: const Text("Button Text"),
color: Colors.indigo,
textColor: Colors.white,
)
)
Forth:
SizedBox( // if use media query, then will not work for nested widgets.
width: double.infinity, //Or use 'width: MediaQuery.of(context).size.width'
child: MaterialButton(
onPressed: () {},
child: const Text("Button Text"),
color: Colors.indigo,
textColor: Colors.white,
)
)
第五点:
Container( // if use media query, then will not work for nested widgets.
width: double.infinity, //Or use 'width: MediaQuery.of(context).size.width'
child: MaterialButton(
onPressed: () {},
child: const Text("Button Text"),
color: Colors.indigo,
textColor: Colors.white,
)
)
在我看来,推荐使用第一种。您也可以将MaterialButton
更改为ElevatedButton
、TextButton
、RaisedButton (已弃用)
或任何其他小部件。
加油!