Naimur Hasan
Naimur Hasan

Reputation: 675

Is there any better approach to pass data to child without stateful, inherited widget?

I've a class like below,

class DottedLine extends StatelessWidget{
  final double circleSize, space;
  final Color color;

  DottedLine({@required this.color, this.circleSize = 1.0, this.space = 5.0});

  @override
  Widget build(BuildContext context){
    return CustomPaint(painter: _DottedLinePainter(color: color, circleSize: circleSize, space: space),);
  }

}

And another class is,

class _DottedLinePainter extends CustomPainter{

  _DottedLinePainter({this.color, this.circleSize, this.space});

  final double circleSize, space;
  final Color color;

  @override
  void paint(Canvas canvas, Size size){
  ...
  }
  ...
}

Here, from DottedLine I'm passing the same three-parameter to the _DottedLinePainter Now If I want to add a new parameter for the class _DottedLinePainter, I've to create it for DottedLine too...

So how can define the parameter name in one place only? But I don't want to extends Inherited Widgets cause if I do, then it foreces me to change DottedLine StatefulWidget which is unneccessary.

Upvotes: 0

Views: 54

Answers (1)

Rémi Rousselet
Rémi Rousselet

Reputation: 277297

You can reduce duplication by directly passing the widget to your custom painter, instead of passing the widget's property:

class DottedLine extends StatelessWidget{
  final double circleSize, space;
  final Color color;

  DottedLine({@required this.color, this.circleSize = 1.0, this.space = 5.0});

  @override
  Widget build(BuildContext context){
    return CustomPaint(painter: _DottedLinePainter(this),);
  }
}

class _DottedLinePainter extends CustomPainter{

  _DottedLinePainter(this.data);

  final DottedLine data;

  @override
  void paint(Canvas canvas, Size size){
  ...
  }
  ...
}

Upvotes: 3

Related Questions