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

如何实现Get.snackbar仅显示一次,避免重复点击触发?

解决Get.snackbar重复点击叠加问题

要实现点击卡片时Snackbar仅显示一次、避免重复叠加,同时弹窗消失后可再次触发,可采用以下两种方案:

方案一:利用GetX内置状态判断

在卡片的点击回调中,先通过Get.isSnackbarOpen判断当前是否有Snackbar处于显示状态,仅当无弹窗时调用Get.snackbar:

void onCardTap() {
  if (!Get.isSnackbarOpen) {
    Get.snackbar(
      'sorry',
      'you missed the game',
      snackPosition: SnackPosition.BOTTOM,
      titleText: Text(
        'sorry',
        style: TextStyle(
          color: Colors.white,
          fontSize: 25,
          fontWeight: FontWeight.bold,
        ),
      ),
      messageText: Text(
        'you missed the game',
        style: TextStyle(
          color: Colors.white,
          fontSize: 20,
        ),
      ),
      backgroundColor: AppColor.colorPrimary,
      borderRadius: 20,
      margin: EdgeInsets.all(20),
      maxWidth: 500,
      animationDuration: Duration(milliseconds: 2000),
      borderColor: Colors.white,
      borderWidth: 3,
    );
  }
}

方案二:自定义状态变量控制

如果需要区分不同类型的Snackbar,可维护一个布尔变量跟踪当前弹窗状态,并通过snackbarStatus回调在弹窗关闭时重置状态:

bool _isTargetSnackbarActive = false;

void onCardTap() {
  if (!_isTargetSnackbarActive) {
    _isTargetSnackbarActive = true;
    Get.snackbar(
      'sorry',
      'you missed the game',
      snackPosition: SnackPosition.BOTTOM,
      titleText: Text(
        'sorry',
        style: TextStyle(
          color: Colors.white,
          fontSize: 25,
          fontWeight: FontWeight.bold,
        ),
      ),
      messageText: Text(
        'you missed the game',
        style: TextStyle(
          color: Colors.white,
          fontSize: 20,
        ),
      ),
      backgroundColor: AppColor.colorPrimary,
      borderRadius: 20,
      margin: EdgeInsets.all(20),
      maxWidth: 500,
      animationDuration: Duration(milliseconds: 2000),
      borderColor: Colors.white,
      borderWidth: 3,
      snackbarStatus: (status) {
        if (status == SnackbarStatus.CLOSED) {
          _isTargetSnackbarActive = false;
        }
      },
    );
  }
}

方案对比

  • 方案一:代码简洁,依赖GetX全局状态判断,适合单一Snackbar场景。
  • 方案二:控制更精准,可同时管理多个不同类型的Snackbar,避免相互干扰。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 22:40:29