当前位置:网站首页>Flutter shared_ Preferences use
Flutter shared_ Preferences use
2022-06-29 08:09:00 【xiangxiongfly915】
List of articles
Flutter shared_preferences Use
sketch
Encapsulate platform specific persistent storage for simple data (iOS and macOS Upper NSUserDefaults, Android Upper SharedPreferences, wait ). Data may be persisted asynchronously to disk , And there is no guarantee that the write will be persisted to the disk after it is returned , So this plug-in cannot be used to store key data .
Add dependency
shared_preferences: ^2.0.15
Basic use
Support data types
int, double, bool, String and List<String>.
Support platform
iOS: NSUserDefaults
Android: SharedPreferences
Web: localStorage
Linux: FileSystem( Save data to the local system file library )
Mac OS: FileSystem( Save data to the local system file library )
Windows: FileSystem( Save data to the local system file library )
Writing data
var sp = await SharedPreferences.getInstance();
sp.setString("name", " Xiao Ming ");
sp.setInt("age", 18);
sp.setBool("sex", true);
sp.setDouble("height", 180.1);
sp.setStringList("address", <String>[" The Beijing municipal ", " Haidian District "]);
Reading data
var sp = await SharedPreferences.getInstance();
String? name = sp.getString("name");
int? age = sp.getInt("age");
bool? sex = sp.getBool("sex");
double? height = sp.getDouble("height");
List<String>? address = sp.getStringList("address");
Delete data
Delete a data
var sp = await SharedPreferences.getInstance();
sp.remove("name");
Clear all data
var sp = await SharedPreferences.getInstance();
sp.clear();
Get all key
var sp = await SharedPreferences.getInstance();
var keys = sp.getKeys();
key Whether there is
var sp = await SharedPreferences.getInstance();
var b = sp.containsKey("name");
encapsulation
Encapsulates the code
import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
class SpUtils {
SpUtils._internal();
factory SpUtils() => _instance;
static late final SpUtils _instance = SpUtils._internal();
static late SharedPreferences _preferences;
static Future<SpUtils> getInstance() async {
_preferences = await SharedPreferences.getInstance();
return _instance;
}
/// according to key Storage int type
static Future<bool> setInt(String key, int value) {
return _preferences.setInt(key, value);
}
/// according to key obtain int type
static int? getInt(String key, {int defaultValue = 0}) {
return _preferences.getInt(key) ?? defaultValue;
}
/// according to key Storage double type
static Future<bool> setDouble(String key, double value) {
return _preferences.setDouble(key, value);
}
/// according to key obtain double type
static double? getDouble(String key, {double defaultValue = 0.0}) {
return _preferences.getDouble(key) ?? defaultValue;
}
/// according to key Storage string type
static Future<bool> setString(String key, String value) {
return _preferences.setString(key, value);
}
/// according to key Get string type
static String? getString(String key, {String defaultValue = ""}) {
return _preferences.getString(key) ?? defaultValue;
}
/// according to key Store Boolean types
static Future<bool> setBool(String key, bool value) {
return _preferences.setBool(key, value);
}
/// according to key Get boolean type
static bool? getBool(String key, {bool defaultValue = false}) {
return _preferences.getBool(key) ?? defaultValue;
}
/// according to key Store an array of string types
static Future<bool> setStringList(String key, List<String> value) {
return _preferences.setStringList(key, value);
}
/// according to key Gets an array of string types
static List<String> getStringList(String key, {List<String> defaultValue = const []}) {
return _preferences.getStringList(key) ?? defaultValue;
}
/// according to key Storage Map type
static Future<bool> setMap(String key, Map value) {
return _preferences.setString(key, json.encode(value));
}
/// according to key obtain Map type
static Map getMap(String key) {
String jsonStr = _preferences.getString(key) ?? "";
return jsonStr.isEmpty ? Map : json.decode(jsonStr);
}
/// Common settings persist data
static set<T>(String key, T value) {
String type = value.runtimeType.toString();
switch (type) {
case "String":
setString(key, value as String);
break;
case "int":
setInt(key, value as int);
break;
case "bool":
setBool(key, value as bool);
break;
case "double":
setDouble(key, value as double);
break;
case "List<String>":
setStringList(key, value as List<String>);
break;
case "_InternalLinkedHashMap<String, String>":
setMap(key, value as Map);
break;
}
}
/// Get persistent data
static dynamic get<T>(String key) {
dynamic value = _preferences.get(key);
if (value.runtimeType.toString() == "String") {
if (_isJson(value)) {
return json.decode(value);
}
}
return value;
}
/// Get all stored data in the persistent data key
static Set<String> getKeys() {
return _preferences.getKeys();
}
/// Gets whether the persistent data contains a key
static bool containsKey(String key) {
return _preferences.containsKey(key);
}
/// Delete one of the persistent data key
static Future<bool> remove(String key) async {
return await _preferences.remove(key);
}
/// Clear all persistent data
static Future<bool> clear() async {
return await _preferences.clear();
}
/// Reload all data , Reload runtime only
static Future<void> reload() async {
return await _preferences.reload();
}
/// Judge whether it is json character string
static _isJson(String value) {
try {
JsonDecoder().convert(value);
return true;
} catch (e) {
return false;
}
}
}
initialization
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await SpUtils.getInstance();
}
Usage 1
Writing data :
SpUtils.setString("name", " Xiao Ming 2");
SpUtils.setInt("age", 28);
SpUtils.setBool("sex", true);
SpUtils.setDouble("height", 180.2);
SpUtils.setStringList("address", <String>[" The Beijing municipal 2", " Haidian District 2"]);
Reading data :
String? name = SpUtils.getString("name");
int? age = SpUtils.getInt("age");
bool? sex = SpUtils.getBool("sex");
double? height = SpUtils.getDouble("height");
List<String>? address = SpUtils.getStringList("address");
Mode 2
Writing data :
SpUtils.set("name", " Xiao Ming 3");
SpUtils.set("age", 38);
SpUtils.set("sex", true);
SpUtils.set("height", 180.3);
SpUtils.set("address", <String>[" The Beijing municipal 3", " Haidian District 3"]);
Reading data :
String? name = SpUtils.get<String>("name");
int? age = SpUtils.get<int>("age");
bool? sex = SpUtils.get<bool>("sex");
double? height = SpUtils.get<double>("height");
List<String>? address = SpUtils.get<List<String>>("address");
边栏推荐
- [eye of depth wuenda machine learning homework class phase IV] summary of logistic regression
- solidity部署和验证代理合约
- Explain the garbage collection mechanism (GC) in JVM
- Segment tree and use
- 软重启(reboot)
- Summary of array knowledge points
- Up and down transitions in polymorphism
- C#导入csv到mysql数据库中
- 【6G】算力网络技术白皮书整理
- Soft restart
猜你喜欢

MySQL系统关键字汇总(官网)
![[repair collection function, update login interface] knowledge payment applet, blog applet, full version open source code, resource realization applet, with 299 whole station resource data](/img/77/328bd10e97d1d78708464c5d59153a.png)
[repair collection function, update login interface] knowledge payment applet, blog applet, full version open source code, resource realization applet, with 299 whole station resource data

aws elastic beanstalk入门之简单使用

Ceres optimization based on sophus

華為雲的AI深潜之旅

Linear regression with one variable

Segment tree and use

AI deep dive of Huawei cloud

MySQL中有哪些约束?(实例验证)

1284_ Implementation analysis of FreeRTOS task priority acquisition
随机推荐
Explanation of swing transformer theory
MySQL system keyword summary (official website)
Oracle batch insert data - insert ethnic data
在colaboratory上云端使用GPU训练(以YOLOv5举例)
solidity部署和验证代理合约
Vulnhub's dc6 target
友元,静态关键字,静态方法以及对象间的关系
Qtcreator set character set
[eye of depth wuenda machine learning homework class phase IV] summary of logistic regression
aws elastic beanstalk入门之简单使用
What are the organizational structure and job responsibilities of product managers in Internet companies?
【深度之眼吴恩达第四期作业班】多元线性回归Linear Regression with multiple variables总结
Line features & surface features of vSLAM features
Cartographer中的线程池操作
自动化测试 - uiautomator2框架应用 - 自动打卡
js实现图片懒加载的一个详细方案(引入即可使用)
软重启(reboot)
C#导入csv到mysql数据库中
mysql 开启日志功能
华为云的AI深潜之旅