You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter ElevatedButton设置onPressed为null后不显示问题求助

Flutter ElevatedButton 设为 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,

后,按钮就能正常显示(见下图),点击时也能触发标准的渐隐按压动画。

切换为null时按钮消失的表现
修改为空回调后的点击动画

有没有人遇到过类似问题?我尝试了多种方法都无法解决。我的运行环境:
Flutter (Channel stable, 3.13.3, on macOS 14.5 23F79 darwin-x64, locale en-DE)


内容的提问来源于stack exchange,提问作者Ala Ha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 04:33:14