Home > front end >  I'm trying to create a optional parameter in constructor but still getting error, can any one h
I'm trying to create a optional parameter in constructor but still getting error, can any one h

Time:12-26

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

  final Color colour;
  final Widget cardChild;

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

This is the error : " The parameter 'cardChild' can't have a value of 'null' because of its type, but the implicit default value is 'null'. "

CodePudding user response:

I don't know what your cardChild code is, but I think the answer you are looking for is this.

class ReusableCard extends StatelessWidget {
  final Color colour;
  final Widget? cardChild;

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

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: const EdgeInsets.all(15.0),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(10.0),
        color: colour,
      ),
      child: cardChild ?? SizedBox(),
    );
  }
}

CodePudding user response:

class ReusableCard extends StatelessWidget {

 final Color colour;
  final Widget cardChild;

//define the variable 1st 
//then call the method
  
ReusableCard({required this.colour, this.cardChild});

 

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

CodePudding user response:

class ReusableCard extends StatelessWidget {
    final Color colour;
    final Widget? cardChild; -------> just add ? for making parameter optional
    ReusableCard({required this.colour, this.cardChild});

CodePudding user response:

class ReusableCard extends StatelessWidget {

 final Color colour;
  final Widget cardChild;

//define the variable 1st 
//then call the method
  
ReusableCard({required this.colour, this.cardChild});

 

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: const EdgeInsets.all(15.0),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(10.0),
        color: colour,
      ),
      // child: cardChild,
    );
  }
}
  • Related