首页 > 解决方案 > 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?

标签: androidxcodeflutterdart

解决方案


使用TextButton.icon -构造函数:

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

这会产生一个按钮,其图标和文本位于一行中。

例如,如果您希望图标位于文本上方,则在 TextButton 中使用一列:

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

推荐阅读