面试题答案
一键面试Row布局类Widget源码解读
- 水平排列处理:
Row
继承自Flex
,Flex
是一个灵活的弹性布局模型。在Row
中,direction
属性默认为Axis.horizontal
,这就决定了子Widget
会沿水平方向排列。- 它会按照子
Widget
在代码中声明的顺序,从左到右依次排列子Widget
。例如:
Row(
children: [
Text('第一个子Widget'),
Text('第二个子Widget')
]
)
这里 Text('第一个子Widget')
会在左边,Text('第二个子Widget')
会在右边。
2. 水平空间分配:
Row
使用弹性布局算法来分配水平空间。它的子Widget
可以通过Flexible
或Expanded
等Widget
来控制对剩余空间的占用。Flexible
允许子Widget
灵活地占用空间,flex
属性控制其在剩余空间中的弹性系数。比如:
Row(
children: [
Flexible(
flex: 1,
child: Container(color: Colors.red),
),
Flexible(
flex: 2,
child: Container(color: Colors.blue),
)
]
)
这里红色容器和蓝色容器会按照 flex
系数 1:2 的比例分配剩余空间。
Expanded
继承自Flexible
,并且flex
属性默认为 1,它会尽可能地占用剩余空间。例如:
Row(
children: [
Text('固定宽度'),
Expanded(
child: Container(color: Colors.green),
)
]
)
这里绿色容器会占用除了 Text('固定宽度')
之外的所有剩余水平空间。
- 对于没有使用
Flexible
或Expanded
的子Widget
,它们会根据自身的width
属性(如果有设置)或者自身内容的大小来占用空间。如果子Widget
没有设置宽度且不是弹性的,它会占用刚好包裹其内容的宽度。