gpt4 book ai didi

flutter - 减少Flutter中的dispose()样板?

转载 作者:行者123 更新时间:2023-12-03 03:14:36 26 4
gpt4 key购买 nike

在Flutter中,我们需要为在dispose()中创建的许多内容写下State,例如

  final _nameController = TextEditingController();

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

因此,我想知道是否有一种方法可以消除这种需求,并自动调用该处理程序?

谢谢!

最佳答案

我找到了另一个解决方案:flutter_hooks

  • 优点:几乎没有样板!
  • 缺点:需要从其他基类(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();
    }
    }

    关于flutter - 减少Flutter中的dispose()样板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62355277/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com