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

Flutter:使用SharedPreferences保存本地通知开关的图标状态

解决Flutter本地通知图标状态重启后丢失的问题

没问题,这个状态丢失的问题很常见,用SharedPreferences就能完美解决。我帮你把代码修改好,加上状态持久化的逻辑,确保重启应用后图标状态能恢复:

步骤1:添加依赖

首先确保你的pubspec.yaml里已经添加了shared_preferences插件:

dependencies:
  flutter:
    sdk: flutter
  shared_preferences: ^2.2.2 # 可以使用最新稳定版本

然后执行flutter pub get安装依赖。

步骤2:修改页面代码

下面是更新后的完整逻辑,我标注了关键修改点:

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

class YourNotificationPage extends StatefulWidget {
  const YourNotificationPage({super.key});

  @override
  State<YourNotificationPage> createState() => _YourNotificationPageState();
}

class _YourNotificationPageState extends State<YourNotificationPage> {
  IconData _icon2 = Icons.notifications_off;
  late SharedPreferences _prefs;
  bool _notificationsEnabled = false; // 用布尔变量记录通知状态,比直接判断图标更可靠

  @override
  void initState() {
    super.initState();
    _loadSavedNotificationStatus(); // 初始化时加载保存的状态
  }

  // 从SharedPreferences读取之前保存的状态
  Future<void> _loadSavedNotificationStatus() async {
    _prefs = await SharedPreferences.getInstance();
    // 读取保存的开关状态,默认是关闭(false)
    _notificationsEnabled = _prefs.getBool('notifications_enabled') ?? false;
    setState(() {
      // 根据读取到的状态更新图标
      _icon2 = _notificationsEnabled ? Icons.notifications_active : Icons.notifications_off;
    });
  }

  // 你的重复通知方法(保留原逻辑)
  void _repeatNotification2() {
    // 原有的通知开启逻辑
  }

  // 你的取消通知方法(保留原逻辑)
  void _cancelNotification2() {
    // 原有的通知关闭逻辑
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('通知设置'),
        actions: [
          IconButton(
            icon: Icon(
              _icon2,
              color: Colors.blue,
              size: 30,
            ),
            onPressed: () async {
              setState(() {
                // 切换状态
                _notificationsEnabled = !_notificationsEnabled;
                // 根据新状态更新图标
                _icon2 = _notificationsEnabled ? Icons.notifications_active : Icons.notifications_off;
              });
              // 将状态保存到SharedPreferences,持久化存储
              await _prefs.setBool('notifications_enabled', _notificationsEnabled);

              // 执行对应的通知操作
              if (_notificationsEnabled) {
                _repeatNotification2();
              } else {
                _cancelNotification2();
              }
            },
          ),
        ],
      ),
    );
  }
}

关键逻辑说明

  • 初始化加载:在initState里调用_loadSavedNotificationStatus,从本地读取之前保存的状态,确保应用重启后能恢复图标和通知状态。
  • 状态持久化:每次点击图标切换状态时,都会把最新的_notificationsEnabled布尔值保存到SharedPreferences里。
  • 状态管理:用布尔变量_notificationsEnabled记录开关状态,比直接判断图标更清晰可靠,避免图标判断出错。

这样修改后,不管你关闭重启多少次应用,图标都会保持上次最后选择的状态啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 14:03:10