我有以下不同按钮变体的代码:
import 'package:flutter/material.dart';
import '../common/texts.dart';
import '../common/colors.dart';
enum ButtonVariant { primary, secondary, text }
enum ButtonState { enabled, disabled, loading }
class CustomButton extends StatelessWidget {
final String text;
final ButtonVariant variant;
final ButtonState state;
final VoidCallback? onPressed;
const CustomButton({
super.key,
required this.text,
this.variant = ButtonVariant.primary,
this.state = ButtonState.enabled,
this.onPressed,
});
@override
Widget build(BuildContext context) {
Color backgroundColor;
Color textColor;
switch (variant) {
case ButtonVariant.primary:
backgroundColor = green500;
textColor = black;
break;
case ButtonVariant.secondary:
backgroundColor = Colors.blue;
textColor = Colors.white;
break;
case ButtonVariant.text:
backgroundColor = Colors.transparent;
textColor = Colors.blue;
break;
}
if (state == ButtonState.disabled) {
backgroundColor = backgroundColor.withOpacity(0.5);
textColor = textColor.withOpacity(0.5);
}
return ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: backgroundColor,
foregroundColor: textColor,
padding: const EdgeInsets.symmetric(vertical: 16.0, horizontal: 24.0),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(22),
),
),
onPressed: state == ButtonState.disabled ? null : onPressed,
child: state == ButtonState.loading
? CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation<Color>(textColor),
)
: Text(text, style: caption2Black),
);
}
}
ElevatedButton 的
onPressed
的正常行为是,如果它是 null
,则该按钮被禁用。
就我而言,该按钮甚至不再显示。一旦我将
onPressed: state == ButtonState.disabled ? null : onPressed,
更改为 onPressed: state == ButtonState.disabled ? () {} : onPressed,
,按钮就会出现(参见 GIF 1)。点击后,按钮上就会出现典型的“淡入淡出”动画(参见 GIF 2)。
还有其他人遇到过这个问题或类似的事情吗?我确实尝试了很多,但没有任何帮助。
我正在跑步
Flutter (Channel stable, 3.13.3, on macOS 14.5 23F79 darwin-x64, locale en-DE)
一开始我无法重现它,但那是因为我没有黑色背景。白色背景效果很好。所以我相信这实际上是因为
ElevatedButton
的默认禁用背景和文本实际上是黑色,具有一定的不透明度。当它被禁用时,它不会查看 backgroundColor
和 foregroundColor
。将这些行添加到 ElevatedButton
应该会给您带来所需的效果:
disabledBackgroundColor: backgroundColor,
disabledForegroundColor: textColor,