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

标签 flutter dart

我上了一个类似于的类(class)

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

在这里,我从 DottedLine 传递相同的三个参数到 _DottedLinePainter 。现在,如果我想为类 _DottedLinePainter 添加新参数,我也要为 DottedLine创建它。

那么如何只在一个地方定义参数名称呢?但是我不想扩展继承的窗口小部件,如果这样做的话,那么它将强制我更改不必要的 DottedLine StatefulWidget。

最佳答案

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

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

关于flutter - 有没有更好的方法来将数据传递给没有状态的,继承的小部件的子级?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59457231/

相关文章:

dart - flutter 错误 : Attempt to invoke virtual method 'void com.google.firebase.auth.internal.zzab.zzf(int)' on a null object reference, 空

flutter - 如何在 Flutter 中播放 Google Drive 中的音乐(mp3、m4a 等)

带有背景音乐的 Flutter App(外部)

flutter - 当小部件从窗口中删除时,不会调用 Dispose - Flutter

flutter - 在我的Flutter应用中实现下一个,上一个主页,共享按钮

Flutter 在相机预览和捕获上显示 Logo

operator-overloading - Dart 你可以重载赋值运算符吗?

flutter - 如何在Flutter中为Container边框的特定边缘着色?

android - Flutter 拨动开关和共享首选项

flutter - 在开发人员选项中更改 “smallest width”时,Flutter UI中断