另外,flutter还分别实现了几个子类,进一步封装了RenderObjectWidget,它们分别是LeafRenderObjectWidget、SingleChildRenderObjectWidget、MultiChildRenderObjectWidget。其中,LeafRenderObjectWidget是叶节点,不含子Widget;SingleChildRenderObjectWidget仅有一个child;而MultiChildRenderObjectWidget则是含有children列表。这几个子类根据child的情况分别创建了对应的Element,所以通过这几个子类,我们只需要关注RenderObject的创建和更新。
(2)用法以最简单的LeafRenderObjectWidget为例,我们需要实现createRenderObject、updateRenderObject两个方法:
class CustomRenderWidget extends LeafRenderObjectWidget { CustomRenderWidget({ this.width = 0, this.height = 0, this.color, }); final double width; final double height; final Color color; @override RenderObject createRenderObject(BuildContext context) { return CustomRenderBox(width, height, color); } @override void updateRenderObject(BuildContext context, RenderObject renderObject) { CustomRenderBox renderBox = renderObject as CustomRenderBox; renderBox ..width = width ..height = height ..color = color; } }