在RenderObject这一层,Flutter已经提供了布局,手势,动画等基础功能,并提供了各种RenderObject共开发者使用。
bool tapped = false; BoxDecoration createDecoration() { return BoxDecoration(color: colorWith(tapped)); } void runRenderImp() { var box = RenderDecoratedBox(decoration: createDecoration()); RenderingFlutterBinding( root: RenderDecoratedBox( decoration: BoxDecoration(color: Color(0xffffffff)), child: RenderPositionedBox( alignment: Alignment.center, child: RenderPointerListener( onPointerUp: (PointerUpEvent event) { tapped = !tapped; box.decoration = createDecoration(); box.reassemble(); }, child: RenderConstrainedBox( child: box, additionalConstraints: BoxConstraints.tight(Size(100, 100)), ))))); }
RenderingFlutterBinding
方法对window
api进行了包装。
布局层次是:
RenderDecoratedBox
,提供纯色背景,
-> RenderPositionedBox
, 居中布局
--> RenderPointerListener
, 处理点击事件
---> 最后是屏幕中间的方块。
这个实现中,没有Canvas对应的绘制逻辑,绘制逻辑由RenderObject
封装。
没有手动的Layout,由RenderPositionedBox
实现居中布局。
RenderPointerListener
提供hit test,开发者只需要实现事件的处理逻辑。
在处理逻辑中,直接修改了RenderDecoratedBox
的decoration(对应于背景色)。然后调用reassemble
方法刷新界面。
这个reassemble
的方法和Android中的invalidate
方法, iOS中的setNeedsDisplay
方法的作用是一致的。
在这一层中,开发体验和Native开发很接近,维护RenderObject Tree, 手动修改属性并触发界面刷新。