hel*_*end 8 dart flutter flutter-layout
在同一个正文中,我试图将一个小部件与屏幕顶部对齐,另一个与屏幕中心对齐。事实证明这很困难。
这是我的代码:
body: Column(children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Container(
color: Colors.redAccent,
width: screenWidth,
height: 50.0,
child: Center(
child: Text(
"Hello World!",
style: TextStyle(
fontSize: 18.0,
color: Colors.white,
),
),
),
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Container(
color: Colors.blueAccent,
width: screenWidth,
height: 50.0,
child: Center(
child: Text(
"Thanks for the help!",
style: TextStyle(
fontSize: 18.0,
color: Colors.white,
),
),
),
),
],
),
]),
Run Code Online (Sandbox Code Playgroud)
当这段代码在我的 Xcode 模拟器中运行时,结果如下:
https://i.imgur.com/JtPKyq0.png
所以要清楚这个结果是错误的,因为我希望蓝色容器位于屏幕的中心,而不是顶部。
在此先感谢您的帮助!
Geo*_*rge 10
一种选择是使用Expanded
小部件。此小部件将展开填充父项中的所有可用空间,然后将子项居中放置在其中。请注意,这仅适用Flex的小部件,如内Row
,Column
等等。
在您的情况下,我还建议删除screenWidth
行宽变量,并使用Expanded
小部件使容器水平填充屏幕。
这是最终的代码:
body: Column(children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Expanded( //makes the red row full width
child: Container(
color: Colors.redAccent,
height: 50.0,
child: Center(
child: Text(
"Hello World!",
style: TextStyle(
fontSize: 18.0,
color: Colors.white,
),
),
),
),
),
],
),
// This expands the row element vertically because it's inside a column
Expanded(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
// This makes the blue container full width.
Expanded(
child: Container(
color: Colors.blueAccent,
height: 50.0,
child: Center(
child: Text(
"Thanks for the help!",
style: TextStyle(
fontSize: 18.0,
color: Colors.white,
),
),
),
),
),
],
),
),
]
),
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
11095 次 |
最近记录: |