更新 child 传递到有状态小部件

Update child passed into stateful widget

您好,我有一个名为 BobButton() 的有状态小部件,它基本上执行动画,按下时按钮会上下摆动。

BobButton animates the child widget with a Bobbing effect (It is Stateful)

我像这样将 child 传递给 BobButton

BobButton( //Statefulwidget
  child: Widget(
    color: color,
    controller: animationController,
  )
)

其中一些小部件具有自己的动画或具有在 parent 小部件状态中发生变化的变量。例如,我可能会调用:

setState({
  color = Colors.pink
});

animationController.forward()

但是小部件不会更新,因为 child 已经传递到有状态小部件 BobButton。

我应该怎么做才能解决这个问题

Widget重写方法

@override
didUpdateWidget(Widget oldWidget) {
  super.didUpdateWidget(oldWidget);
  if (widget.color != oldWidget.color) {
    setState(() {
      //  states variables if neccessary
    });
  }
}

AnimationController 是一个 Listenable,因此您可以添加一个侦听器。或者尝试检查 didUpdateWidget 方法中的 value 更改,如上所述。