有没有更好的方法将数据传递给没有有状态、继承的小部件的子级?



我有一个像下面的类,

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),);
}
}

另一类是,

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

在这里,我从虚线将相同的三个参数传递给_DottedLinePainter现在如果我想为类_DottedLinePainter添加一个新参数,我也必须为虚线创建它......

那么如何在一个地方只定义参数名称呢?但是我不想扩展继承的小部件,因为如果我这样做,那么它就预示着我更改虚线状态小部件,这是不必要的。

您可以通过直接将小部件传递给自定义绘制器来减少重复,而不是传递小部件的属性:

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

最新更新