简体   繁体   中英

How can i put icon inside custom button in flutter

I have custom button. I want to put the icons inside these custom buttons, i always got error to code for this situation and i couldn't get it to work.

  class CustomButton extends StatelessWidget {
  final Function onTap;
  final String btnTxt;
  final Color backgroundColor;
  final Icon icon;
  CustomButton({this.onTap, @required this.btnTxt, this.backgroundColor, this.icon});

  @override
  Widget build(BuildContext context) {
    final ButtonStyle flatButtonStyle = TextButton.styleFrom(
      backgroundColor: onTap == null ? ColorResources.getGreyColor(context) : backgroundColor == null ? Theme.of(context).primaryColor : backgroundColor,
      minimumSize: Size(MediaQuery.of(context).size.width, 50),
      padding: EdgeInsets.zero,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(10),
      ),
    );

    return TextButton(
      onPressed: onTap,
      style: flatButtonStyle,
      child: Text(btnTxt??"",
          style: Theme.of(context).textTheme.headline3.copyWith(color: ColorResources.COLOR_WHITE, fontSize: Dimensions.FONT_SIZE_LARGEi)),
    );
  }
}

I tried button->style-> icon(Icons.bla bla) and got an error how can I fix it?

Use the TextButton.icon -constructor:

return TextButton.icon(
  onPressed: onTap,
  style: flatButtonStyle,
  icon: icon,
  label: Text(btnTxt, style: ...)
)

This results in a button with the icon and the text positioned in a row.

If you want the icon to be eg positioned above the text, then use a column in the TextButton:

TextButton(
  onPressed: ...,
  style: ...
  child: Column(
    mainAxisSize: MainAxisSize.min,
    children: [icon, Text(btnTxt)],
  )
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM