Flutter基础(三)

自定义控件

Posted by Ted on March 11, 2019

1、自定义控件

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

使用的时候

CustomComponent(
  icons: Icons.comment,
  btnName: '评论',
),

或者换一种定义方式

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

使用的方式

CustomComponent(
    Icons.favorite_border,
    '喜欢',
)