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'),],),),);}}注意事项
shared_preferences只适合存储简单的键值对数据,不适合存储大量或复杂的数据结构。- 存储的数据是异步的,需要使用
await等待操作完成。 - 数据会持久化存储,即使应用关闭后数据仍然存在。
- 在 iOS 上,数据存储在 NSUserDefaults 中;在 Android 上,数据存储在 SharedPreferences 中。
- 在 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 官方文档
