1. Flutter Expanded
Expanded 是一个小部件,有助于根据主轴扩展 Row 或 Column 的子小部件的空间。需要注意的是,Row 的主轴是水平轴,Column 的主轴是垂直轴。
Expanded构造函数
const Expanded(
{Key key,
int flex: 1,
@required Widget child}
)
首先,请以下图为例。在这个例子中,一个 Row 对象有五个子部件。注意是如何水平扩展第二个和第四个子部件的空间。
示例:
Row (
children: [
ElevatedButton(child: Text("B1"), onPressed:(){}),
Icon(Icons.ac_unit, size: 32, color: Colors.red),
ElevatedButton(
child: Text("B2"),
onPressed:(){},
style: ButtonStyle(
minimumSize: MaterialStateProperty.all(Size(50, 100))
)
),
Icon(Icons.add_circle, size: 96, color: Colors.green),
ElevatedButton(child: Text("Btn 3"), onPressed:(){}),
]
)
将 Row 子部件包装在 Expanded 对象中有助于它水平扩展空间并占用其余的 Row 空间。
示例代码:
Row (
children: [
ElevatedButton(child: Text("B1"), onPressed:(){}),
Expanded(
child: Icon(Icons.ac_unit, size: 32, color: Colors.red),
),
ElevatedButton(
child: Text("B2"),
onPressed:(){},
style: ButtonStyle(
minimumSize: MaterialStateProperty.all(Size(50, 100))
)
),
Expanded(
child: Icon(Icons.add_circle, size: 96, color: Colors.green),
),
ElevatedButton(child: Text("Btn 3"), onPressed:(){}),
]
)
2. child属性
@required Widget child
3. flex属性
flex 属性被认为是 Expanded 的权重。它确定将分配多少空间给 Expanded。分配的空间与 flex 值成正比。flex 的默认值为 1
。
int flex: 1
示例代码如下:
Row (
children: [
ElevatedButton(child: Text("B1"), onPressed:(){}),
Expanded(
child: Icon(Icons.ac_unit, size: 32, color: Colors.red),
flex: 3
),
ElevatedButton(
child: Text("B2"),
onPressed:(){},
style: ButtonStyle(
minimumSize: MaterialStateProperty.all(Size(50, 100))
)
),
Expanded(
child: Icon(Icons.add_circle, size: 96, color: Colors.green),
flex: 2
),
ElevatedButton(child: Text("Btn 3"), onPressed:(){}),
]
)
示例效果图如下:
flex属性示例代码2:
Column (
children: [
ElevatedButton(child: Text("B1"), onPressed:(){}),
Expanded(
child: Icon(Icons.ac_unit, size: 32, color: Colors.red),
flex: 3
),
ElevatedButton(
child: Text("B2"),
onPressed:(){},
style: ButtonStyle(
minimumSize: MaterialStateProperty.all(Size(90, 30))
)
),
Expanded(
child: Icon(Icons.add_circle, size: 96, color: Colors.green),
flex: 2
),
ElevatedButton(child: Text("Btn 3"), onPressed:(){}),
]
)
示例效果图如下: