Flutter:在父状态更改时重新渲染子窗口小部件

Her*_*ine 5 dart flutter

因此 a 拥有一个具有timer值的有状态父级。该计时器可由用户重置。我还有一个带有动画控制器的子有状态小部件。父级将timer值传递给子级以重置动画。这是一些代码:

class _ParentState extends State<Parent> {
  int timer = 20;
  
  void _userInput() {
    setState(() {
      timer = 20;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Child(
      time: timer
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

注意:为了简单起见,这是条带化的

因此,当我的用户触发该_userInput方法时,计时器值会改变,但孩子不会改变。这是我的完整子小部件:

class TimerProgress extends StatefulWidget {
  TimerProgress({
    Key key,
    @required this.time,
    @required this.onCompleted
  }) : super(key: key);

  final int time;
  final Function onCompleted;

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

class _TimerProgressState extends State<TimerProgress> with SingleTickerProviderStateMixin {
  AnimationController _controller;
  Animation<double> _widthAnimation;

  @override
  void initState() {
    _controller = AnimationController(
      duration: Duration(seconds: widget.time),
      vsync: this
    );

    _widthAnimation = Tween<double>(
      begin: 200,
      end: 0
    ).animate(CurvedAnimation(
      parent: _controller,
      curve: Curves.linear
    ));

    _controller.addListener(() {
      if (_controller.value == 1) {
        widget.onCompleted();
      }
    });

    _controller.forward();

    super.initState();
  }

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

  @override
  Widget build(BuildContext context) {
    return ...
  }
}
Run Code Online (Sandbox Code Playgroud)

所以这一切都有效,但理想情况下我希望重置动画,但这不起作用......

mig*_*uno 4

initState每个状态实例仅运行一次。

实现重置内部时间didUpdateWidgethttps://api.flutter.dev/flutter/widgets/RawScrollbarState/didUpdateWidget.html

您不能(因为它会导致递归循环,setState将再次触发didUpdateWidget)并且不应该(在调用此方法之后,build正在被调用)必须setState在该方法内部调用。

可运行示例:https ://www.dartpad.dev/848976603f866f4e3aa6030aba8addf7?null_safety=true

在此输入图像描述