如何使一个小部件从另一个小部件继承? -颤抖

时间:2019-07-04 10:32:43

标签: inheritance flutter dart

我希望能够从具有一些属性的基本IconButton继承。从此类继承的按钮应该可以访问基类属性,而不会覆盖它们。

class BaseButton extends StatelessWidget {
  final IconData icon;
  final double size;
  final Color color;
  final Function onPressed;
  const BaseButton({
    Key key,
    this.icon,
    this.size = 30,
    this.color = Colors.white,
    this.onPressed,
  }) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return IconButton(
      onPressed: onPressed,
      icon: Icon(icon),
      iconSize: size,
      color: color,
    );
  }
}

我想使用这个基类来生成具有很少麻烦的小部件:

class AddButton extends BaseButton {
  @override
  Widget build(BuildContext context) {
    return BaseButton(icon: Icons.add);
  }
}

class CancelButton extends BaseButton {
  @override
  Widget build(BuildContext context) {
    return BaseButton(icon: Icons.close);
  }
}

而且我希望能够轻松访问继承的基类的属性。

1 个答案:

答案 0 :(得分:0)

认为您想要类似的东西:

class AddButton extends BaseButton {

  const AddButton({
    Key key,
    double size,
    Color color,
    this.onPressed,
  }) : super(key: key, icon: Icons.add, size: size, color: color, onPressed: onPressed);
}

class CancelButton extends BaseButton {

 const CancelButton({
    Key key,
    double size,
    Color color,
    this.onPressed,
  }) : super(key: key, icon: Icons.close, size: size, color: color, onPressed: onPressed);
}

无需覆盖AddButton或CancelButton中的构建。