代码之家  ›  专栏  ›  技术社区  ›  Rémi Rousselet

如何热重新加载状态字段?

  •  2
  • Rémi Rousselet  · 技术社区  · 6 年前

    如何热重新加载 State 颤振子类?

    我知道在热重新加载期间不考虑修改字段的初始值,我可以对它们使用热重新启动。但这是令人痛苦的缓慢。

    有什么方法可以简化这个过程吗?

    一个典型的用例是动画,特别是 AnimationController . 因为它存储在状态字段中,但我们通常希望在其持续时间内迭代。例子:

    class MyAnim extends StatefulWidget {
      @override
      _MyAnimState createState() => _MyAnimState();
    }
    
    class _MyAnimState extends State<MyAnim> with SingleTickerProviderStateMixin {
      AnimationController animationController;
    
      @override
      void initState() {
        animationController =
            AnimationController(vsync: this, duration: const Duration(seconds: 1));
        super.initState();
      }
    
      @override
      void dispose() {
        animationController.dispose();
        super.dispose();
      }
    
      @override
      Widget build(BuildContext context) {
        return Container();
      }
    }
    
    1 回复  |  直到 6 年前
        1
  •  4
  •   Rémi Rousselet    6 年前

    状态为热重新加载提供自定义生命周期挂钩: reassemble

    您可以自由地重写该方法以具有自定义的热重新加载行为。别担心,在生产中永远不会调用此方法。

    稍微调整一下,你会得到以下信息:

    class _MyAnimState extends State<MyAnim> with SingleTickerProviderStateMixin {
      AnimationController animationController;
    
      @override
      void initState() {
        animationController = AnimationController(vsync: this);
        _initializeFields();
        super.initState();
      }
    
      void _initializeFields() {
        animationController.duration = const Duration(seconds: 1);
      }
    
      @override
      void reassemble() {
        _initializeFields();
        super.reassemble();
      }
    
      @override
      void dispose() {
        animationController.dispose();
        super.dispose();
      }
    
      @override
      Widget build(BuildContext context) {
        return Container();
      }
    }
    

    现在,无论何时修改状态类,它都将正确更新 AnimationController 持续时间。