簡體   English   中英

減少 Flutter 中 dispose() 的樣板?

[英]Reduce the boilerplate of dispose() in Flutter?

在 Flutter 中,我們需要為我們在State中創建的許多東西寫下dispose() ,例如

  final _nameController = TextEditingController();

  @override
  void dispose() {
    _nameController.dispose();
    super.dispose();
  }

因此,我想知道是否有辦法消除這種需要,並自動調用 dispose?

謝謝!

我找到了另一個解決方案: flutter_hooks

  • 優點:幾乎沒有樣板!
  • 缺點:需要從不同的基礎 class 擴展(HookWidget,不是 StatefulWidget)

一個樣本:

前 -

class Example extends StatefulWidget {
  final Duration duration;

  const Example({Key key, @required this.duration})
      : assert(duration != null),
        super(key: key);

  @override
  _ExampleState createState() => _ExampleState();
}

class _ExampleState extends State<Example> with SingleTickerProviderStateMixin {
  AnimationController _controller;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(vsync: this, duration: widget.duration);
  }

  @override
  void didUpdateWidget(Example oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.duration != oldWidget.duration) {
      _controller.duration = widget.duration;
    }
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container();
  }
}

后 -

class Example extends HookWidget {
  final Duration duration;

  const Example({Key key, @required this.duration})
      : assert(duration != null),
        super(key: key);

  @override
  Widget build(BuildContext context) {
    final controller = useAnimationController(duration: duration);
    return Container();
  }
}

你有幾個選擇:

  1. 如果在您需要處置一些對象的每個State中重寫dispose方法是可以的,只需創建一個您需要處置的所有對象的列表,然后一次對它們調用dispose 像這樣的東西應該工作:
  @override
  void dispose() {
    [objectToDispose1, objectToDispose2, objectToDispose3].forEach((o) => o.dispose());
    super.dispose();
  }
  1. 如果您只是不想重寫 dispose 方法,那么您需要將 go 回到 OOP 的基礎。 反射在這里會非常方便,但 Flutter 出於性能原因不允許它。 因此,您可以創建自己的抽象基礎 class 擴展State ,可能稱為DisposableState 這個抽象的 class 將有一個抽象的 getter 用於將對象作為List進行處置。 然后,它將使用選項 1 中的上述方法在其 dispose 方法中引用該 getter:
  List get disposables;

  @override
  void dispose() {
    disposables.forEach((o) => o.dispose());
    super.dispose();
  }

注意:您可以使用具有close()而不是dispose()的對象擴展這兩個選項,稍作修改會添加更多樣板:(

Unfortunately, I believe this is the shortest way to go about mass-disposing objects as they have to be "registered" for disposal/closing somewhere, and afaik, the Flutter framework does not provide any way to do this in the basic State class.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM