具有空安全性的必需值和可选值的无状态小部件

Stateless widget with required and optional values with null safety

所以我正在尝试创建一个可以在我的 flutter 应用程序中使用的自定义小部件。创建此小部件时,我想始终 select 一种颜色(因此需要值),但我想保留 cardChild 和 onpres 值可选。我该怎么做呢?我试图给一个空容器和空函数作为默认值,但后来我得到了错误

error: The default value of an optional parameter must be constant. (non_constant_default_value at [untitled1] lib/Components/reusable_card.dart:6)

这是我的小部件构造函数:

class ReusableCard extends StatelessWidget {ReusableCard(
{required this.colour, this.cardChild = Container(), this.onPress = () {}});

  final Color colour;
  final Widget cardChild;
  final Function onPress;

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        onPress;
      },
      child: Container(
        child: cardChild,
        margin: EdgeInsets.all(15.0),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.all(Radius.circular(15.0)),
          color: colour,
        ),
      ),
    );
  }
}

您可以通过在构造函数中设置 cardChildonPress 位置参数来实现。

class ReusableCard extends StatelessWidget {

  //constructor
  ReusableCard(this.colour,this.cardChild, this.onPress);

  final Color colour;
  final Widget cardChild;
  final Function onPress;

  @override
  Widget build(BuildContext context) {
  ....
  

或通过添加 ?:

使它们可以为空
  class ReusableCard extends StatelessWidget {

  //constructor
  ReusableCard({required this.colour, this.cardChild, this.onPress});

  final Color colour;
  final Widget? cardChild;
  final Function? onPress;

  @override
  Widget build(BuildContext context) {
  ....

为了更好地理解命名参数和位置参数,请阅读 this

您可以使用以下方法

    class ReusableCard extends StatelessWidget {ReusableCard(
        {required this.colour, this.cardChild, this.onPress});
    
    final Color colour;
    final Widget? cardChild;
    final Function? onPress;
    
    @override
    Widget build(BuildContext context) {
      return GestureDetector(
        onTap: () {
          if(onPress != null){
            onPress!();
          }
        },
        child: Container(
          child: cardChild ?? Container(),
          margin: EdgeInsets.all(15.0),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.all(Radius.circular(15.0)),
            color: colour,
          ),
        ),
      );
    }
  }