Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter: Are RenderObjects recreated during lifetime of a StatefulWidget?

Tags:

flutter

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();
  }

  // ...
}
like image 932
boformer Avatar asked Sep 15 '25 17:09

boformer


1 Answers

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.

like image 190
Rémi Rousselet Avatar answered Sep 17 '25 09:09

Rémi Rousselet