Flutter ElevatedButton设置onPressed为null后不显示问题求助
我编写了一个支持多种样式与状态的自定义按钮组件,代码如下:
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,
后,按钮就能正常显示(见下图),点击时也能触发标准的渐隐按压动画。


有没有人遇到过类似问题?我尝试了多种方法都无法解决。我的运行环境:Flutter (Channel stable, 3.13.3, on macOS 14.5 23F79 darwin-x64, locale en-DE)
内容的提问来源于stack exchange,提问作者Ala Ha
相关产品推荐
相关产品推荐

