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

Flutter中使用shared_preferences保存themeColor的位置咨询

实现背景色持久化方案

你的themeColor变量位置没问题,依然放在_ColorSaveState类里作为状态变量,只需要结合shared_preferences做初始化读取和变更时保存两个操作即可实现持久化,具体步骤和代码如下:

1. 添加依赖

在项目的pubspec.yaml中添加shared_preferences依赖:

dependencies:
  flutter:
    sdk: flutter
  shared_preferences: ^2.2.2 # 可替换为最新版本

执行flutter pub get拉取依赖。

2. 完整实现代码

class _ColorSaveState extends State<ColorSave> {
  // themeColor依然作为组件状态变量放在此处
  late Color themeColor;

  @override
  void initState() {
    super.initState();
    // 组件初始化时读取已保存的颜色
    _loadSavedColor();
  }

  // 从shared_preferences读取保存的颜色配置
  Future<void> _loadSavedColor() async {
    final prefs = await SharedPreferences.getInstance();
    // 读取颜色标识,默认值为red100
    final savedColorKey = prefs.getString('theme_color') ?? 'red100';
    
    setState(() {
      switch(savedColorKey) {
        case 'blue':
          themeColor = Colors.blue;
          break;
        case 'green':
          themeColor = Colors.green;
          break;
        default:
          themeColor = Colors.red[100]!;
          break;
      }
    });
  }

  // 更改背景色并同步保存到shared_preferences
  Future<void> colorBackground(String color) async {
    final prefs = await SharedPreferences.getInstance();
    setState(() {
      if(color == "themeBlue"){
        themeColor = Colors.blue;
        prefs.setString('theme_color', 'blue');
      }else{
        themeColor = Colors.green;
        prefs.setString('theme_color', 'green');
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: const Text('ColorSave'),
        backgroundColor: Colors.blue,
      ),
      backgroundColor: themeColor,
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children:<Widget>[
            InkWell(
              child: Container(
                width: 100,
                height: 100,
                color: Colors.blue,
              ),
              onTap: (){
                colorBackground("themeBlue");
              },
            ),
            const SizedBox(height: 20),
            InkWell(
              child: Container(
                width: 100,
                height: 100,
                color: Colors.green,
              ),
              onTap: (){
                colorBackground("themeGreen");
              },
            ),
          ]
        )
      )
    );
  }
}

关键说明

  • themeColor作为组件的状态变量,必须放在State类中,这样才能通过setState触发UI更新。
  • shared_preferences仅支持保存基本数据类型(字符串、数字等),因此无法直接存储Color对象,我们用字符串标识(如'blue'、'green')来映射对应的颜色值。
  • 在initState中异步读取保存的配置,确保组件启动时就能加载用户之前设置的背景色。
  • 每次调用colorBackground更改颜色时,同步将对应的标识保存到shared_preferences,实现持久化。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 02:07:31