Flutter基础(三)

2022-06-07 14:28:11 浏览数 (1)

1、自定义控件
代码语言:javascript复制
class CustomComponent extends StatefulWidget {
  final IconData icons;
  final MaterialColor color;
  final String btnName;
  final GestureTapCallback onTap;

  CustomComponent(
      {@required this.icons,
      @required this.btnName,
      this.color = Colors.grey,
      this.onTap});

  @override
  State<CustomComponent> createState() {
    return CustomComponentState();
  }
}

class CustomComponentState extends State<CustomComponent> {
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Icon(widget.icons, color: widget.color),
          Text(widget.btnName, style: TextStyle(color: widget.color))
        ],
      ),
      onTap: widget.onTap,
    );
  }
}

使用的时候

代码语言:javascript复制
CustomComponent(
  icons: Icons.comment,
  btnName: '评论',
),

或者换一种定义方式

代码语言:javascript复制
CustomComponent(this.icons, this.btnName, {this.color= Colors.grey, this.onTap});

使用的方式

代码语言:javascript复制
CustomComponent(
    Icons.favorite_border,
    '喜欢',
)

0 人点赞