本文共 3437 字,大约阅读时间需要 11 分钟。
移动开发中常常会对各个Widget进行布局,本文主要介绍了Flutter中最基本的三种布局方式:Row、Column、Stack。从字面意思,我们也可以理解到,Row对应Android中的LinearLayout,orientation为Horizontal。Column对应于Android中的LinearLayout,orientation为Vertical。Stack对应于Android中的RelativeLayout,可以通过添加相应子控件,设置目标控件在父控件的布局规则。下面我们通过几个简单的例子介绍这三种布局控件的基本用法。
一.Row/Column
Row和Column分别为水平布局和垂直布局,这两个布局控件具有相同的属性值,只是其子控件的方向不同。这里我们重点了解下mainAxisAlignment和crossAxisAlignment两个属性,也就是主轴和交叉轴的概念。
对于Row来说,水平方向就是主轴,垂直方向就是横轴,对于Column来说,垂直方向就是主轴,水平方向就是横轴。
其中MainAxisAlignment枚举值:
CrossAxisAlignment枚举值有如下几种:
示例代码:
Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.spaceBetween, children:[ Text('Hello', style: TextStyle(fontSize: 48),), Text('world', style: TextStyle(fontSize: 24),) ],),Row( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ Text('Hello', style: TextStyle(fontSize: 48),), Text('world', style: TextStyle(fontSize: 24),) ],),Row( crossAxisAlignment: CrossAxisAlignment.end, mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Text('Hello', style: TextStyle(fontSize: 48),), Text('world', style: TextStyle(fontSize: 24),) ],),
显示效果:
值得注意的是,Row和Column自身不带滚动属性,如果超出了一行,在debug下面则会显示溢出的提示。当子空间超出页面时,如添加了ListView控件,可在外面包裹一层Expanded控件。
当需要对子空间进行等分布局时,可使用Flex示例:
child: Column( children:[ Expanded( flex: 1, child: Container(color: Colors.red), ), Expanded( flex: 2, child: Container(color: Colors.green), ), Expanded( flex: 1, child: Container(color: Colors.blue), ), ],)
效果:
在Stack中可通过两种方式来定位子控件的位置,分别为使用Positioned包裹子控件及使用Align包裹子控件。我们先来看一段示例代码:
Container( padding: EdgeInsets.all(16), color: Colors.grey, height: 200, child: Stack( children:[ Positioned( top: 2, left: 10, child: Text('top_2_left_10'), ), Positioned( top: 2, right: 10, child: Text('top_2_right_10'), ), Positioned( bottom: 2, right: 10, child: Text('bottom_2_right_10'), ), Positioned( bottom: 2, left: 10, child: Text('bottom_2_left_10'), ), Align( alignment: Alignment.centerLeft, child:Text('Left', style: TextStyle(fontSize: 15)) ), Align( alignment: Alignment.center, child:Text('Center', style: TextStyle(fontSize: 15)) ), Align( alignment: Alignment.centerRight, child:Text('Right', textAlign: TextAlign.right, style: TextStyle(fontSize: 15)) ) ], ),),
显示效果如下图:
其中,Postioned可设置子控件在父控件中的对齐方式:左对齐,右对齐,顶部对齐,底部对齐。并通过设置具体数值设置上下左右距离各边的距离。
Align控件可通过设置其属性值alignment,定位子控件在父控件中的位置。对齐子控件的方式有:
本文主要介绍了Flutter中的三种最基本的布局方式,我们可以通过灵活运用各种布局方式及其辅助控件实现我们想要的效果。
作者:DASH_1024 链接:https://www.jianshu.com/p/17eada6ec320 来源:简书 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。