Search code examples
flutterflutter-layoutflutter-dependenciesflutter-animationflutter-widget

How to change the value of a member in a custom widget dynamically based on a changing value passed from outside


I am new to flutter. I was trying to make a custom widget that uses Bézier curve to draw a gooey circle, which changes its position based on the value of the slider.

I have made a gif to show what I was up to.GooeyCircle

The problem is, I need to change the gooey circle's position(progress) based on _sliderValue, but it seems that the progress in the GooeyCircleWidget stays the initial value and never changes whenever the slider goes. I want it to be passed into the widget dynamically, could anyone please help me find out what I should do? Thanks!

GooeyCircleWidget(
              progress: _sliderValue,
              color: Colors.blue,
            ),
class GooeyCircleWidget extends StatefulWidget {
  Color color;
  double progress ;

  _GooeyCircleWcoloridgetState createState() => _GooeyCircleWidgetState(
    progress: progress,
    color:color,
  );
  GooeyCircleWidget({
   @required this.progress,
   this.color
});å
}

class _GooeyCircleWidgetState extends State<GooeyCircleWidget>
    with SingleTickerProviderStateMixin {
  final double progress;
  AnimationController controller;
  final Color color;

  _GooeyCircleWidgetState(
      {@required this.progress,
        this.color});


  @override
  void initState() {
    super.initState();
    controller = AnimationController(vsync: this);


  }


  @override
  Widget build(BuildContext context) {
    print(progress);
    // TODO: implement build
    return CustomPaint(
      painter: AnimatedCirclePainter( 
      progress: progress,
      color: color,
      ),
      size: Size(1080, 200),
    );
  }
}

Solution

  • Don't pass the variables from GooeyCircleWidget into the constructor of _GooeyCircleWidgetState. Instead use widget.

    Like so:

    class GooeyCircleWidget extends StatefulWidget {
      Color color;
      double progress ;
    
      @override
      _GooeyCircleWidgetState createState() => _GooeyCircleWidgetState();
    
      GooeyCircleWidget({
       @required this.progress,
       this.color,
      });
    }
    
    class _GooeyCircleWidgetState extends State<GooeyCircleWidget>
        with SingleTickerProviderStateMixin {
      AnimationController controller;
    
      @override
      void initState() {
        super.initState();
        controller = AnimationController(vsync: this);
      }
    
      @override
      Widget build(BuildContext context) {
        print(widget.progress);
        // TODO: implement build
        return CustomPaint(
          painter: AnimatedCirclePainter( 
          progress: widget.progress,
          color: widget.color
          ),
          size: Size(1080, 200),
        );
      }
    }