制作全宽按钮的方法有很多种。但我认为你应该理解在不同场景下制作全宽度小部件的概念:
当你使用嵌套小部件时,很难识别父小部件的宽度。简单地说,您不能在嵌套的小部件中指定宽度。所以你应该使用扩展或列与CrossAxisAlignment拉伸。
在其他情况下,您可以使用媒体查询宽度或double.infinity。
这里有一些嵌套小部件和单个小部件的例子:
第一:
Expanded( // This will work for nested widgets and will take width of first parent widget.
child: MaterialButton(
onPressed: () {},
child: const Text("Button Text"),
color: Colors.indigo,
textColor: Colors.white,
)
)
第二:
Column( // This will not work if parent widget Row.
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,
)
)
出:
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(折旧)或任何其他小部件。
干杯!