1

The SoC parameter of the widget is not available from the start. So, I'd like my animation tween to actually takes the SoC when it is no longer null.

But because I construct my animation within the initState() I don't get a chance to do so.

What would be the best architecture for this widget?


class SocGaugeWidget extends StatefulWidget {
  final double? soc;

  SocGaugeWidget({Key? key, required this.soc}) : super(key: key);

  State<SocGaugeWidget> createState() => _SocGaugeWidget();
}

class _SocGaugeWidget extends State<SocGaugeWidget>
    with SingleTickerProviderStateMixin {
  late final Animation<double> animation;
  late final AnimationController controller;

  @override
  void initState() {
 
    // == The animation
    controller =
        AnimationController(vsync: this, duration: Duration(seconds: 1));
    animation =
        Tween<double>(begin: 0, end: widget.soc ?? 10).animate(controller)
          ..addListener(() {
            setState(() {});
          })
          ..addStatusListener((status) {
            if (status == AnimationStatus.completed) {
              controller.reverse();
            } else if (status == AnimationStatus.dismissed) {
              controller.forward();
            }
          });

    controller.forward();

    super.initState();
  }

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

  Widget build(BuildContext context) { 
    return Text("${animation.value}");
  }
}
Stéphane de Luca
  • 12,745
  • 9
  • 57
  • 95
  • when `soc` is null you can return sizedBox, also check before controller. I think better to check the usecase of this current widget. like `if(value!=null)SocGaugeWidget()` – Md. Yeasin Sheikh Dec 19 '22 at 17:56
  • 1
    Using `didUpdateWidget` lifecycle method to call `forward()` will start the animation everytime the widget configuration changes – Gwhyyy Dec 19 '22 at 19:00

0 Answers0