当前位置:网站首页>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");
边栏推荐
- 【修复收藏功能、更新登录接口】知识付费小程序、博客小程序、完整版开源源码、资源变现小程序,带299整站资源数据
- Pointer reference array element
- AI and the meta universe sparked a spark: human beings lost only shackles and gained all-round liberation
- 【kerberos】kerberos 认证浅析
- Code:: blocks code formatting shortcuts
- 反思 - 中小公司项目管理思维 - 先将产品做出来,先将功能做出来
- Django - installing mysqlclient error: mysqlclient 1.4.0 or newer is required; you have 0.9.3
- Qtcreator set character set
- php 清除多维数组里面的空值
- code::blocks代码格式化快捷键
猜你喜欢

Introduction to taro

Thread pool operations in cartographer

基于Sophus的Ceres优化

ROS当中的仿真时间以及Bag包操作

【深度之眼吴恩达机器学习作业班第四期】Regularization正则化总结

What are the organizational structure and job responsibilities of product managers in Internet companies?

Explain the garbage collection mechanism (GC) in JVM
![[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

线段树以及使用

1284_ Implementation analysis of FreeRTOS task priority acquisition
随机推荐
Up and down transitions in polymorphism
Codeforces Round #799 (Div. 4)
常见的七大排序
SVM, problems encountered in face recognition and Solutions
Audio and video development cases 99 lectures - Contents
手撕二叉搜索树(Binary Search Tree)
基于Sophus的Ceres优化
Binary search tree
code::blocks代码格式化快捷键
mysql 开启日志功能
Explanation of swing transformer theory
Vulnhub's dc6 target
Common MySQL errors and solutions summarized painstakingly (I)
IndexTree以及应用
【深度之眼吴恩达第四期作业班】多元线性回归Linear Regression with multiple variables总结
C # import CSV into MySQL database
[eye of depth Wu Enda's fourth operation class] summary of multiple linear regression with multiple variables
solidity部署和验证代理合约
Development trend of garment industry | supply chain | intelligent manufacturing
Indextree and Application