I have a setup where a StatefulWidget creates a custom (leaf) RenderBox. Is there are possibility that the RenderBox is disposed and recreated during the lifetime of the State?
Background. I want to keep certain results of heavy calculations/animation controllers in the RenderObject, that's why it is important for me that the RenderObject lives as long as the State of the enclosing widget.
import 'package:flutter/widgets.dart';
class SquaredCircle extends StatefulWidget {
  const SquaredCircle({Key key, this.radius}) : super(key: key);
  final double radius;
  @override
  State<StatefulWidget> createState() => _SquaredCircleState();
}
class _SquaredCircleState extends State<SquaredCircle> {
  int _squareness = 42;
  @override
  Widget build(BuildContext context) {
    final foo = widget.radius * _squareness;
    return _SquaredCircleRenderObjectWidget(foo);
  }
}
class _SquaredCircleRenderObjectWidget extends LeafRenderObjectWidget {
  _SquaredCircleRenderObjectWidget(this.foo);
  final double foo;
  @override
  _RenderSquaredCircle createRenderObject(BuildContext context) {
    return _RenderSquaredCircle(foo: foo);
  }
  @override
  void updateRenderObject(BuildContext context, _RenderSquaredCircle renderObject) {
    renderObject..foo = foo;
  }
}
class _RenderSquaredCircle extends RenderBox {
  _RenderSquaredCircle({double foo})
      : assert(foo != null),
        _foo = foo;
  double get foo => _foo;
  double _foo;
  set foo(double value) {
    assert(value != null);
    if (_foo == value) return;
    _foo = value;
    markNeedsPaint();
  }
  // ...
}
A RenderObject will not be disposed until you replace it by another RenderObject of a different type, or remove the associated widget from the widget tree.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With