Flutter: re-render child widget on parent state change

Viewed 2743

So a have a stateful parent with a timer value. This timer can be reset by the user. I also have a child stateful widget with an animation controller. The parent passes the timer value to this child to reset the animation. Here is some code:

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

  @override
  Widget build(BuildContext context) {
    return Child(
      time: timer
    );
  }
}

Note: this is striped down for simplicity

So when my user triggers the _userInput method, the timer value gets changed but the child doesn't. Here is my full child widget:

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 ...
  }
}

So this all works, but ideally I want the animation to be reset, which doesn't work...

1 Answers
Related