如何对带有或不带有图标的ElevatedButton应用不同的样式

问题描述 投票:0回答:1

在我的应用程序中,我有很多

ElevatedButtons
,我在主主题中设置了样式。我需要将带图标的样式设置为与不带图标的样式不同的样式。

这是只有一个属性的代码,但是适用于所有

ElevatedButtons
,我如何选择带有 图标的属性并给它们一个不同的
borderRadius

@override
Widget build(BuildContext context) {
  return MaterialApp(
    theme: ThemeData(
      elevatedButtonTheme: ElevatedButtonThemeData(
        style: ElevatedButton.styleFrom(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(10.0),
          ),
        ),
      ),
    ),
  );
}
flutter button themedata
1个回答
0
投票

为了实现这一目标,我建议创建一个自定义小部件作为提升按钮的包装。示例:

class CustomButton extends StatelessWidget {
  final Icon? icon;
  final VoidCallback? onPressed;
  final Widget child;

  const CustomButton({
    super.key,
    required this.child,
    this.icon,
    this.onPressed,
  });

  @override
  Widget build(BuildContext context) {
    return icon != null
        ? ElevatedButton.icon(
            onPressed: onPressed,
            icon: icon!,
            label: child,
            style: ElevatedButton.styleFrom(
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(50.0),
              ),
            ))
        : ElevatedButton(
            onPressed: onPressed,
            style: ElevatedButton.styleFrom(
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(10.0),
              ),
            ),
            child: child,
          );
  }
}

icon
参数可以为空(可选),如果设置了它,它应该构建一个具有指定样式的
ElevatedButton.icon
。否则,它会根据自己的风格构建一个标准的风格(应该与
ElevatedButton.icon
的风格不同)。

输出:

无图标:

CustomButton(
    onPressed: () {},
    child: const Text('Elevated Button'),
),

enter image description here

带有图标:

CustomButton(
    icon: const Icon(Icons.add),
    onPressed: () {},
    child: const Text('Icon Elevated Button'),
),

enter image description here


请注意,如果您想将样式保留在主应用程序小部件的

style
中,则可以删除标准按钮(无图标)的
ThemeData
。但是,我不推荐它,因为会有一个明确的小部件来处理提升按钮的外观。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.