Flutter Align控件用法
Align用来确定子控件在父布局中的位置,定义如下
const Align({
Key key,
this.alignment = Alignment.center,
this.widthFactor,
this.heightFactor,
Widget child,
})
alignment属性设置子控件的位置,Alignment中已定义了如下几种位置:
- Alignment.topLeft:顶部左边
- Alignment.topCenter:顶部中间
- Alignment.topRight:顶部右边
- Alignment.centerLeft:中部左边
- Alignment.center:中部中间
- Alignment.centerRight:中部右边
- Alignment.bottomLeft:底部左边
- Alignment.bottomCenter:底部中间
- Alignment.bottomRight:底部右边
我们直接写个示例看下效果就知道具体表示的位置:
如下所示,有一个容器,里面有一个Flutter图标,位于容器中部的右边,其他方位大家可以自己改下代码看下效果,这里不再多做说明
Container(
width: 300,
height: 300,
color: Colors.green[100],
child: Align(
alignment: Alignment.centerRight,
child: FlutterLogo(size: 60)
)
)
看源码可以发现以上定义的位置其实都是Alignment常量,如下所示
/// The top left corner.
static const Alignment topLeft = Alignment(-1.0, -1.0);
/// The center point along the top edge.
static const Alignment topCenter = Alignment(0.0, -1.0);
/// The top right corner.
static const Alignment topRight = Alignment(1.0, -1.0);
/// The center point along the left edge.
static const Alignment centerLeft = Alignment(-1.0, 0.0);
/// The center point, both horizontally and vertically.
static const Alignment center = Alignment(0.0, 0.0);
/// The center point along the right edge.
static const Alignment centerRight = Alignment(1.0, 0.0);
/// The bottom left corner.
static const Alignment bottomLeft = Alignment(-1.0, 1.0);
/// The center point along the bottom edge.
static const Alignment bottomCenter = Alignment(0.0, 1.0);
/// The bottom right corner.
static const Alignment bottomRight = Alignment(1.0, 1.0);
所以对于中间右边位置,如下代码效果也是一样的
Container(
width: 300,
height: 300,
color: Colors.green[100],
child: Align(
alignment: Alignment(1.0, 0.0),
child: FlutterLogo(size: 60)
)
)
Alignment中的第一第二个参数分别表示x轴和y轴的的偏移,以矩形的中心点为坐标原点,x轴从-1到1表示矩形的左边到右边的距离,y轴从-1到1表示矩形顶部到底部的距离
所以除了以上预定义的9个方位外,我们还可以通过Alignment将子控件放在任何一个位置