Flutter 入门笔记(Part 3) 布局

9 . 布局容器

9.1 Container,Padding,Center

  • Container内部提供了间距,背景样式,圆角边框等基础属性,可以控制子Widget的摆放方式(居中,左,右)
  • Padding 设置间距,将Widget放里面
  • Center 设置居中,将Widget放里面
getContainer() {
return Container(
  child: Center(
    child: Text('Container(容器)在UI框架中是一个很常见的概念,Flutter也不例外。'),
  ),
  //内边距
  padding: EdgeInsets.all(18.0),
  //外边距
  margin: EdgeInsets.all(44.0),
  width: 180.0,
  height: 240,
  //子Widget居中对齐
  /* alignment: Alignment.center,*/
  //Container样式
  decoration: BoxDecoration(
    //背景色
    color: Colors.red,
    //圆角边框
    borderRadius: BorderRadius.circular(10.0),
  ),
);
}

getPadding() {
//只需要设置边距 可以使用Padding
return Padding(
  padding: EdgeInsets.all(44.0),
  child: Text('我是Padding'),
);
}

getCenter() {
//直接居中
return Center(
  child: Text('center text'),
);
}

9.2 Row,Column,Expanded

  • Row是水平布局
  • Column是垂直布局
  • Expanded表示将剩余的空间,如何分配
  • Row 与 Column 自身的大小由父widget的大小、子widget的大小、以及mainSize设置共同决定(mainAxisSize和crossAxisSize)
  • 主轴(纵轴)值为max:主轴(纵轴)大小等于屏幕主轴(纵轴)方向大小或者父widget主轴(纵轴)方向大小
  • 主轴(纵轴)值为min:所有子widget组合在一起的主轴(纵轴)大小
//Row的用法示范
Row(
  children: <Widget>[
    Container(color: Colors.yellow, width: 60, height: 80,),
    Container(color: Colors.red, width: 100, height: 180,),
    Container(color: Colors.black, width: 60, height: 80,),
    Container(color: Colors.green, width: 60, height: 80,),
  ],
);

//Column的用法示范
Column(
  children: <Widget>[
    Container(color: Colors.yellow, width: 60, height: 80,),
    Container(color: Colors.red, width: 100, height: 180,),
    Container(color: Colors.black, width: 60, height: 80,),
    Container(color: Colors.green, width: 60, height: 80,),
  ],
);


//第一个和最后一个平分
Row(
  children: <Widget>[
    Expanded(flex: 1, child: Container(color: Colors.yellow, height: 60)), //设置了flex=1,因此宽度由Expanded来分配
    Container(color: Colors.red, width: 100, height: 180,),
    Container(color: Colors.black, width: 60, height: 80,),
    Expanded(flex: 1, child: Container(color: Colors.green,height: 60),)/设置了flex=1,因此宽度由Expanded来分配
  ],
);

「对齐方式」

  • 根据主轴与纵轴,设置子Widget在这两个方向上的对齐规则mainAxisAlignment与crossAxisAlignment.比如主轴方向start表示靠左对齐,center表示横向居中对齐,end表示靠右对齐,spaceEvenly表示按固定间距对齐;而纵轴方向start则表示靠上对齐,center表示纵向居中对齐,end表示靠下对齐.

「控制大小」

  • 如果想让容器与子Widget在主轴上完全匹配,需要通过设置Row的mainAxisSize参数为MainAxisSize.min,由所有子Widget来决定主轴方向的容器长度,即主轴方向的长度尽可能小.类似wrap_content. mainAxisSize: MainAxisSize.min, //让容器宽度与所有子Widget的宽度一致

9.3 Stack,Positioned

  • Stack,类似FrameLayout.
  • Stack提供了层叠布局的容器,而Positioned则提供了设置子Widget位置的能力.

Stack(
  children: <Widget>[
    Container(color: Colors.yellow, width: 300, height: 300),//黄色容器
    Positioned(
      left: 18.0,
      top: 18.0,
      child: Container(color: Colors.green, width: 50, height: 50),//叠加在黄色容器之上的绿色控件
    ),
    Positioned(
      left: 18.0,
      top:70.0,
      child: Text("Stack提供了层叠布局的容器"),//叠加在黄色容器之上的文本
    )
  ],
)
  • Positioned只能在Stack中使用.

手机扫码阅读