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

Flutter如何实现点击ElevatedButton后禁用双按钮且重启应用仍保持禁用状态

功能实现方案

1. 引入持久化依赖

我们使用官方维护的shared_preferences实现状态本地持久化,首先在项目pubspec.yaml文件中添加依赖:

dependencies:
  flutter:
    sdk: flutter
  # 新增以下依赖,版本可根据官方最新稳定版调整
  shared_preferences: ^2.2.2

添加完成后执行flutter pub get拉取依赖包。

2. 完整业务代码实现

整体逻辑如下:

  • 定义布尔变量_isButtonsEnabled控制按钮状态,默认值为true
  • 页面初始化时读取本地存储的按钮状态,同步到当前变量
  • 任意按钮点击后,先执行业务逻辑,再将禁用状态写入本地存储,同步更新页面状态
  • 支持两种效果:按钮禁用(onPressed传null自动变为禁用样式)、按钮隐藏(用Visibility组件包裹控制显隐),可按需选择
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:shared_preferences/shared_preferences.dart';

class HospitalVotePage extends StatefulWidget {
  final String hospitalName;
  const HospitalVotePage({super.key, required this.hospitalName});

  @override
  State<HospitalVotePage> createState() => _HospitalVotePageState();
}

class _HospitalVotePageState extends State<HospitalVotePage> {
  bool _isButtonsEnabled = true;
  // 本地存储的key,避免硬编码
  static const String _buttonDisabledKey = "vote_buttons_disabled";

  @override
  void initState() {
    super.initState();
    _loadButtonStatus();
  }

  // 初始化时读取本地存储的按钮状态
  Future<void> _loadButtonStatus() async {
    final prefs = await SharedPreferences.getInstance();
    // 如果存储里没有对应值,默认返回false,也就是按钮默认可用
    bool isDisabled = prefs.getBool(_buttonDisabledKey) ?? false;
    setState(() {
      _isButtonsEnabled = !isDisabled;
    });
  }

  // 点击后设置按钮为禁用状态,写入本地存储
  Future<void> _setButtonsDisabled() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setBool(_buttonDisabledKey, true);
    setState(() {
      _isButtonsEnabled = false;
    });
  }

  // 你原有业务方法,这里保留示例
  void positiveIncrement(String hospitalName) {
    // 原有逻辑不变
  }
  void negativeIncrement(String hospitalName) {
    // 原有逻辑不变
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: [
        // 如果需要隐藏按钮,就把ElevatedButton用Visibility包裹,visible设为_isButtonsEnabled即可
        ElevatedButton(
          // 按钮可用时才绑定点击事件,不可用时传null自动变为禁用样式
          onPressed: _isButtonsEnabled ? () {
            positiveIncrement(widget.hospitalName);
            // 执行业务逻辑后设置按钮禁用
            _setButtonsDisabled();
          } : null,
          child: Text(
            "Yes",
            style: GoogleFonts.lexendMega(),
          ),
          style: ElevatedButton.styleFrom(
            // 禁用状态下会自动使用灰色,你也可以自定义禁用状态的颜色
            primary: const Color(0xFF87D68D),
          ),
        ),
        ElevatedButton(
          onPressed: _isButtonsEnabled ? () {
            negativeIncrement(widget.hospitalName);
            _setButtonsDisabled();
          } : null,
          child: Text(
            "No",
            style: GoogleFonts.lexendMega(),
          ),
          style: ElevatedButton.styleFrom(
            primary: const Color(0xFFE3655B),
          ),
        ),
      ],
    );
  }
}

效果切换说明

  • 如果需要实现按钮隐藏效果,只需要给两个ElevatedButton分别包裹Visibility组件,设置visible: _isButtonsEnabled即可,应用重启后同样会保持隐藏状态
  • 如果需要重置按钮状态,只需调用SharedPreferences.getInstance()后调用remove(_buttonDisabledKey)清除存储值即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 05:15:02