前言
接着上一篇 Flutter 布局详解(一) 我们继续深入学习,探索约束传递与尺寸确定,以加深巩固。
源码分析
void main() {
runApp(const ColoredBox(color: Colors.blue));
}
class ColoredBox extends SingleChildRenderObjectWidget {
...
RenderObject createRenderObject(BuildContext context) {
return _RenderColoredBox(color: color);
}
}
- 控制本质
RenderObjectWidget
负责布局,通过重写createRenderObject
,在ColoredBox
中是_RenderColoredBox
负责渲染组件
class _RenderColoredBox extends RenderProxyBoxWithHitTestBehavior {
...
void paint(PaintingContext context, Offset offset) {
if (size > Size.zero) {
context.canvas.drawRect(offset & size, Paint()..color = color);
}
if (child != null) {
context.paintChild(child!, offset);
}
}
}
abstract class RenderProxyBoxWithHitTestBehavior extends RenderProxyBox {
...
}
class RenderProxyBox extends RenderBox with RenderObjectWithChildMixin<RenderBox>, RenderProxyBoxMixin<RenderBox> {
...
}
- 发现 canvas 绘制当前组件的
size
决定组件的尺寸大小,定义在 RenderBox _RenderColoredBox
继承RenderProxyBoxWithHitTestBehavior
继承RenderProxyBox
继承RenderBox
混入RenderObjectWithChildMixin
abstract class RenderBox extends RenderObject {
...
set size(Size value) {
...
_size = value;
assert(() {
debugAssertDoesMeetConstraints();
return true;
}());
}
}
- 断点此处
_size = value;
发现是mix
类RenderProxyBoxMixin
执行performLayout()
发现 size 的赋值size = computeSizeForNoChild(constraints);