当前位置: 首页 > news >正文

flutter轻量级本地存储shared_preferences 教程

shared_preferences

本文档将介绍如何在 Flutter 应用中使用 shared_preferences 插件进行本地数据持久化存储。

介绍

shared_preferences是 Flutter 中用于轻量级数据持久化的插件,适用于存储简单的键值对数据,如用户设置、应用配置等。它封装了 iOS 的 NSUserDefaults 和 Android 的 SharedPreferences。

安装

pubspec.yaml文件中添加依赖:

dependencies:shared_preferences:^2.2.2

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

属性

属性名类型说明
get(String key)Future<Object?>获取指定键的值
getBool(String key)Future<bool?>获取布尔值
getInt(String key)Future<int?>获取整数值
getDouble(String key)Future<double?>获取双精度浮点数值
getString(String key)Future<String?>获取字符串值
getStringList(String key)Future<List?>获取字符串列表
setBool(String key, bool value)Future设置布尔值
setInt(String key, int value)Future设置整数值
setDouble(String key, double value)Future设置双精度浮点数值
setString(String key, String value)Future设置字符串值
setStringList(String key, List<String> value)Future设置字符串列表
remove(String key)Future删除指定键
clear()Future清除所有数据
containsKey(String key)Future检查键是否存在
getKeys()Set获取所有键的集合
reload()Future重新加载数据

基本用法

引入包

import'package:shared_preferences/shared_preferences.dart';

获取 SharedPreferences 实例

// 获取实例finalprefs=awaitSharedPreferences.getInstance();

存储数据

// 存储字符串awaitprefs.setString('username','John Doe');// 存储整数awaitprefs.setInt('age',30);// 存储布尔值awaitprefs.setBool('isLoggedIn',true);// 存储双精度浮点数awaitprefs.setDouble('height',1.75);// 存储字符串列表awaitprefs.setStringList('favorites',['apple','banana','orange']);

读取数据

// 读取字符串String?username=prefs.getString('username');// 读取整数int?age=prefs.getInt('age');// 读取布尔值bool?isLoggedIn=prefs.getBool('isLoggedIn');// 读取双精度浮点数double?height=prefs.getDouble('height');// 读取字符串列表List<String>?favorites=prefs.getStringList('favorites');

删除数据

// 删除单个键awaitprefs.remove('username');// 清除所有数据awaitprefs.clear();

检查键是否存在

// 检查键是否存在bool hasKey=prefs.containsKey('username');

完整示例

import'package:flutter/material.dart';import'package:shared_preferences/shared_preferences.dart';classSharedPreferencesExampleextendsStatefulWidget{constSharedPreferencesExample({Key?key}):super(key:key);@overrideState<SharedPreferencesExample>createState()=>_SharedPreferencesExampleState();}class_SharedPreferencesExampleStateextendsState<SharedPreferencesExample>{finalTextEditingController_usernameController=TextEditingController();finalTextEditingController_ageController=TextEditingController();bool _isLoggedIn=false;String_savedUsername='';int?_savedAge;@overridevoidinitState(){super.initState();_loadData();}Future<void>_loadData()async{finalprefs=awaitSharedPreferences.getInstance();setState((){_savedUsername=prefs.getString('username')??'';_savedAge=prefs.getInt('age');_isLoggedIn=prefs.getBool('isLoggedIn')??false;});}Future<void>_saveData()async{finalprefs=awaitSharedPreferences.getInstance();awaitprefs.setString('username',_usernameController.text);awaitprefs.setInt('age',int.tryParse(_ageController.text)??0);awaitprefs.setBool('isLoggedIn',_isLoggedIn);await_loadData();}Future<void>_clearData()async{finalprefs=awaitSharedPreferences.getInstance();awaitprefs.clear();await_loadData();}@overrideWidgetbuild(BuildContextcontext){returnScaffold(appBar:AppBar(title:constText('SharedPreferences 示例'),),body:Padding(padding:constEdgeInsets.all(16.0),child:Column(crossAxisAlignment:CrossAxisAlignment.start,children:[TextField(controller:_usernameController,decoration:constInputDecoration(labelText:'用户名'),),TextField(controller:_ageController,decoration:constInputDecoration(labelText:'年龄'),keyboardType:TextInputType.number,),SwitchListTile(title:constText('登录状态'),value:_isLoggedIn,onChanged:(value){setState((){_isLoggedIn=value;});},),constSizedBox(height:20),ElevatedButton(onPressed:_saveData,child:constText('保存数据'),),ElevatedButton(onPressed:_clearData,child:constText('清除数据'),),constSizedBox(height:20),Text('已保存的用户名:$_savedUsername'),Text('已保存的年龄:$_savedAge'),Text('登录状态:$_isLoggedIn'),],),),);}}

注意事项

  1. shared_preferences只适合存储简单的键值对数据,不适合存储大量或复杂的数据结构。
  2. 存储的数据是异步的,需要使用await等待操作完成。
  3. 数据会持久化存储,即使应用关闭后数据仍然存在。
  4. 在 iOS 上,数据存储在 NSUserDefaults 中;在 Android 上,数据存储在 SharedPreferences 中。
  5. 在 Web 平台上,数据存储在 localStorage 中。

常见问题

Q: shared_preferences 可以存储自定义对象吗?

A: 不可以直接存储自定义对象,但可以将对象转换为 JSON 字符串后再存储:

// 存储awaitprefs.setString('user',jsonEncode(user.toJson()));// 读取String?userJson=prefs.getString('user');if(userJson!=null){Useruser=User.fromJson(jsonDecode(userJson));}

Q: shared_preferences 的数据存储在哪里?

A: 不同平台存储位置不同:

  • iOS: NSUserDefaults
  • Android: SharedPreferences
  • Web: localStorage
  • Linux: 文件系统
  • macOS: NSUserDefaults
  • Windows: 文件系统

Q: shared_preferences 有什么限制?

A: 主要限制包括:

  • 只能存储基本数据类型(String, int, bool, double, List)
  • 不适合存储大量数据
  • 不适合存储复杂的数据结构

相关链接

  • shared_preferences 官方文档
  • Flutter 官方文档
http://www.cnnetsun.cn/news/2134757.html

相关文章:

  • Phi-4-mini-reasoning企业落地:保险条款自动推理与理赔逻辑校验系统
  • ICode竞赛通关后,如何用Python函数自制编程小游戏?
  • 实测对比:三家安卓加固方案防GG修改器的实战效果哪家强?
  • 最终收官课:从刷题到实战 —— 数据结构与算法的工业界真相
  • GPFS 集群运维「神器」:手搓一个 EC 模式可视化监控平台,实现自动化飞书告警!
  • 避坑指南:博途程序加密后忘记密码怎么办?手把手教你用存储卡清除S7-1200 PLC密码
  • JACP-317120电源模块
  • 别再只会用open和close了!Tcl文件读写实战:从读取日志到批量处理文本的5个真实场景
  • Pixel Couplet Gen微信小程序实战:Canvas渲染像素春联并支持长按保存
  • 逃离塔科夫离线训练器:5分钟掌握30+功能,新手秒变老玩家
  • 情侣互动小程序开发实战:从零构建任务积分系统
  • 程序员编程助手科技股份有限责任公司AIRecomandationWebSys技术经理四川大学计算机学院毕业生技术官微软技术工程师12年工作经验后端技术微软工程师
  • Qt信号槽跨线程传自定义类型?别踩坑了!手把手教你用qRegisterMetaType搞定
  • BiliTools终极指南:三步轻松下载B站高清视频与弹幕
  • 嵌入式Linux驱动开发(7) 从虚拟设备到真实硬件 —— LED驱动硬件基础
  • OpenProject开源项目管理平台:基于Ruby on Rails的企业级协同解决方案
  • 移动端PDF预览技术选型方案:pdfh5.js企业级架构解析
  • what(): EGL error xc at eglBindAPI 已放弃 (核心已转储)
  • Gazebo仿真调试利器:手把手教你用gz log工具记录和回放任意时刻的世界状态
  • 手把手教你用MSP430F5529的DMA+ADC实现多通道数据采集(附电赛避坑指南)
  • NCCL拓扑发现与Channel搜索:你的多GPU训练效率,可能就由这俩算法决定
  • Radeon Software Slimmer终极指南:如何让AMD显卡驱动轻量化75%
  • Auto-Unlocker:如何高效解除VMware对macOS虚拟机的系统限制
  • 【第1章·第27节】不同控制器的应用场合总结与分析
  • Rockchip RK3538与RK3572芯片架构与应用解析
  • 无线串口对传模块:4G全网通适配,远程串口无缝对接
  • 郭明錤爆料:OpenAI 计划 2028 年量产手机,欲重构手机交互逻辑
  • wxauto终极指南:5分钟打造你的Windows微信自动化助手
  • 【车规级激光雷达数据处理SOP】:从Velodyne VLP-16到Livox Mid-70,3类硬件适配的4层C++抽象架构
  • 终极解决方案:5分钟智能激活Windows和Office全系列版本