Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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。

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
551 views
Welcome To Ask or Share your Answers For Others

1 Answer

未传参数本就是null了

this.pressed=null

改为

this.pressed

置灰在build时后判断即可


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...