Flutter:在StatefulWidget的生命周期内是否重新创建了RenderObject?

时间:2018-07-22 12:06:55

标签: flutter

我有一个设置,其中StatefulWidget创建了一个自定义(叶子)RenderBoxRenderBox是否有可能在State的生存期内被处置并重新创建?

背景。我想在RenderObject中保留繁重的计算/动画控制器的某些结果,这就是为什么RenderObject的生存时间与封闭小部件的State一样长的原因。< / p>

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

  // ...
}

1 个答案:

答案 0 :(得分:1)

RenderObject不会被处置,除非您用另一种不同类型的RenderObject替代它,或者从小部件树中删除关联的小部件。