layer property Null safety

ContainerLayer? layer

The compositing layer that this render object uses to repaint.

If this render object is not a repaint boundary, it is the responsibility of the paint method to populate this field. If needsCompositing is true, this field may be populated with the root-most layer used by the render object implementation. When repainting, instead of creating a new layer the render object may update the layer stored in this field for better performance. It is also OK to leave this field as null and create a new layer on every repaint, but without the performance benefit. If needsCompositing is false, this field must be set to null either by never populating this field, or by setting it to null when the value of needsCompositing changes from true to false.

If a new layer is created and stored in some other field on the render object, the render object must use a LayerHandle to store it. A layer handle will prevent the layer from being disposed before the render object is finished with it, and it will also make sure that the layer gets appropriately disposed when the render object creates a replacement or nulls it out. The render object must null out the LayerHandle.layer in its dispose method.

If this render object is a repaint boundary, the framework automatically creates an OffsetLayer and populates this field prior to calling the paint method. The paint method must not replace the value of this field.


ContainerLayer? get layer {
  assert(!isRepaintBoundary || _layerHandle.layer == null || _layerHandle.layer is OffsetLayer);
  return _layerHandle.layer;
void layer=(ContainerLayer? newLayer)


set layer(ContainerLayer? newLayer) {
    'Attempted to set a layer to a repaint boundary render object.\n'
    'The framework creates and assigns an OffsetLayer to a repaint '
    'boundary automatically.',
  _layerHandle.layer = newLayer;