在以下布局中,我希望按钮能够在屏幕上尽可能扩大到最大宽度。我已经尝试了以下操作,但不起作用(按钮始终尽可能宽):
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: SafeArea(
child: Center(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
TextFormField(),
TextFormField(),
ConstrainedBox(
constraints: BoxConstraints(maxWidth: 200),
child: RaisedButton(child: Text("button"), onPressed: () {}),
),
],
),
),
),
),
);
}
}
为了扩展我正在寻找的布局:按钮的宽度必须与以下两个数量中较小的一个相同:1)屏幕的宽度,2)给定的固定最大宽度。
示例场景:
A)屏幕为1000像素宽,给定的固定最大宽度为600像素,则按钮将为600像素宽。
B)屏幕为400像素宽,给定的固定最大宽度为600像素,则按钮将为400像素宽。
您可以删除crossAxisAlignment: CrossAxisAlignment.stretch
,因为TextFormField
仍在伸展。此代码将使按钮的宽度为最大宽度,但不大于屏幕宽度:
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) => MaterialApp(
home: Scaffold(
body: SafeArea(
child: Center(
child: Column(
children: [
TextFormField(),
TextFormField(),
Container(
width: 200,
child: RaisedButton(
onPressed: () {},
child: Text('button'),
),
),
Container(
width: 200,
child: RaisedButton(
onPressed: () {},
child: Text(
'Button with long text asf sadf sdf as df s df as '
'dfas dfsd f asfauhiusg isdugfisudgfi asudgk usgkdu'
'ksdfhk sudfhk sudhfk',
),
),
),
],
),
),
),
),
);
}
您可以将RaisedButton
放入Row
:
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: SafeArea(
child: Center(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
TextFormField(),
TextFormField(),
ConstrainedBox(
constraints: BoxConstraints(maxWidth: 250),
child: Row(
children: <Widget>[
Expanded(
child: RaisedButton(child: Text('test')),
),
],
),
),
],
),
),
),
),
);
}
}
Row
将创建一个水平行,RaisedButton
小部件将仅占用其自身大小的空间。
[According to the documentation,可以用ButtonTheme
覆盖。