flutter 我试图在构造函数中创建一个可选参数,但仍然出错,有人能帮我吗?

2eafrhcq  于 2022-12-27  发布在  Flutter
关注(0)|答案(4)|浏览(124)
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,
    );
  }
}

这是错误:参数"cardChild"的值不能为"null",因为其类型不同,但隐式默认值为"null"。

yhived7q

yhived7q1#

我不知道你的cardChild代码是什么,但我认为你正在寻找的答案是这样的。

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

gcmastyq2#

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

toe950273#

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

wdebmtf24#

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

相关问题