flutter 自定义组件 初始化方法参数默认值该如何设置?

class MyBtn extends StatelessWidget {
  final text;
  final double width;
  final double height;
  final Color color;
  final pressed;
  const MyBtn(
      {this.text = "", this.width = 80, this.height = 80,this.color=Colors.red,this.pressed=null});

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Container(
        height: this.height,
        width: this.width,
        child: RaisedButton(
          color: this.color,
          child: Text(this.text),
          onPressed:this.pressed
        ));
  }
}

这里我是要自定义一个按钮组件,初始化一些默认参数,
width,height,color,text,以及onpress事件

MyBtn(
            text: "自定义按钮",
            height: 60.0,
            width: 120.0,
            color:Colors.yellow,
          )

在调用的过程中,如果我们没有传入点击事件方法,那么按钮就会直接置灰,没有点击事件,而当我在
`const MyBtn(

  {this.text = "", this.width = 80, this.height = 80,this.color=Colors.red,this.pressed=null});`

定义构造函数时,this.pressed 有警告 "Don't explicitly initialize variables to null."不要把初始化参数设置为null。

假如我需要自定义一个按钮组件,当我传入方法参数时 执行传入方法,否则执行默认参数方法,应该如何实现?

阅读 9.9k
1 个回答

未传参数本就是null了

this.pressed=null

改为

this.pressed

置灰在build时后判断即可

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题