当前位置:网站首页>[shutter] SharedPreferences
[shutter] SharedPreferences
2022-07-27 10:26:00 【It Zhi male】
1. Introduce dependencies
# https://github.com/tekartik/synchronized.dart
synchronized: '>=3.0.0 <4.0.0'
# https://github.com/flutter/plugins/tree/master/packages/shared_preferences
shared_preferences: '>=2.0.3 <4.0.0'
2. SpUtil
library sp_util;
import 'dart:async';
import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:synchronized/synchronized.dart';
/** * @Author: Sky24n * @GitHub: https://github.com/Sky24n * @Email: [email protected] * @Date: 2018/9/8 * @Description: Sp Util. */
/// SharedPreferences Util.
class SpUtil {
static SpUtil? _singleton;
static SharedPreferences? _prefs;
static Lock _lock = Lock();
static Future<SpUtil?> getInstance() async {
if (_singleton == null) {
await _lock.synchronized(() async {
if (_singleton == null) {
// keep local instance till it is fully initialized.
// Keep the local instance until it is fully initialized .
var singleton = SpUtil._();
await singleton._init();
_singleton = singleton;
}
});
}
return _singleton;
}
SpUtil._();
Future _init() async {
_prefs = await SharedPreferences.getInstance();
}
/// put object.
static Future<bool>? putObject(String key, Object value) {
return _prefs?.setString(key, json.encode(value));
}
/// get obj.
static T? getObj<T>(String key, T f(Map v), {
T? defValue}) {
Map? map = getObject(key);
return map == null ? defValue : f(map);
}
/// get object.
static Map? getObject(String key) {
String? _data = _prefs?.getString(key);
return (_data == null || _data.isEmpty) ? null : json.decode(_data);
}
/// put object list.
static Future<bool>? putObjectList(String key, List<Object> list) {
List<String>? _dataList = list.map((value) {
return json.encode(value);
}).toList();
return _prefs?.setStringList(key, _dataList);
}
/// get obj list.
static List<T>? getObjList<T>(String key, T f(Map v),
{
List<T>? defValue = const []}) {
List<Map>? dataList = getObjectList(key);
List<T>? list = dataList?.map((value) {
return f(value);
}).toList();
return list ?? defValue;
}
/// get object list.
static List<Map>? getObjectList(String key) {
List<String>? dataLis = _prefs?.getStringList(key);
return dataLis?.map((value) {
Map _dataMap = json.decode(value);
return _dataMap;
}).toList();
}
/// get string.
static String? getString(String key, {
String? defValue = ''}) {
return _prefs?.getString(key) ?? defValue;
}
/// put string.
static Future<bool>? putString(String key, String value) {
return _prefs?.setString(key, value);
}
/// get bool.
static bool? getBool(String key, {
bool? defValue = false}) {
return _prefs?.getBool(key) ?? defValue;
}
/// put bool.
static Future<bool>? putBool(String key, bool value) {
return _prefs?.setBool(key, value);
}
/// get int.
static int? getInt(String key, {
int? defValue = 0}) {
return _prefs?.getInt(key) ?? defValue;
}
/// put int.
static Future<bool>? putInt(String key, int value) {
return _prefs?.setInt(key, value);
}
/// get double.
static double? getDouble(String key, {
double? defValue = 0.0}) {
return _prefs?.getDouble(key) ?? defValue;
}
/// put double.
static Future<bool>? putDouble(String key, double value) {
return _prefs?.setDouble(key, value);
}
/// get string list.
static List<String>? getStringList(String key,
{
List<String>? defValue = const []}) {
return _prefs?.getStringList(key) ?? defValue;
}
/// put string list.
static Future<bool>? putStringList(String key, List<String> value) {
return _prefs?.setStringList(key, value);
}
/// get dynamic.
static dynamic getDynamic(String key, {
Object? defValue}) {
return _prefs?.get(key) ?? defValue;
}
/// have key.
static bool? haveKey(String key) {
return _prefs?.getKeys().contains(key);
}
/// contains Key.
static bool? containsKey(String key) {
return _prefs?.containsKey(key);
}
/// get keys.
static Set<String>? getKeys() {
return _prefs?.getKeys();
}
/// remove.
static Future<bool>? remove(String key) {
return _prefs?.remove(key);
}
/// clear.
static Future<bool>? clear() {
return _prefs?.clear();
}
/// Fetches the latest values from the host platform.
static Future<void>? reload() {
return _prefs?.reload();
}
///Sp is initialized.
static bool isInitialized() {
return _prefs != null;
}
/// get Sp.
static SharedPreferences? getSp() {
return _prefs;
}
}
3. initialization
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await SpUtil.getInstance();
runApp(_widgetForRoute(window.defaultRouteName));
}
After initialization, it can be used directly .
4. matters needing attention
- Flutter Of sp The generated file is in data/data/ Package name /shared_prefs/ Under the folder


If mixed development , The primary end andFlutterEnd calls are somewhat different , As shown above , yesflutterThe end call is generated by the following codeFlutterSharedPreferences.xml
SpUtil.putString("result", "test");
flutter We don't need to specify the file name , And after generation ,name Automatic addition flutter., Above key stay sp The file becomes flutter.result. and Flutter obtain result The corresponding values are as follows :
String? sp = SpUtil.getString("result");
If the native side wants to get flutter Created sp, You need the following methods :
SharedPreferences sp = context.getSharedPreferences("FlutterSharedPreferences",
Context.MODE_PRIVATE);
String value = sp.getString("flutter.result", "");
- Errors may be reported during mixed development :
E/flutter (28814): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: MissingPluginException(No implementation found for method getAll on channel plugins.flutter.io/shared_preferences)
Solution : stay Android Native end FlutterActivity perhaps FlutterFragment Add the following code
@Override
public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) {
super.configureFlutterEngine(flutterEngine);
GeneratedPluginRegistrant.registerWith(flutterEngine);
}
边栏推荐
- Different binary conversion of MATLAB
- warning: remote HEAD refers to nonexistent ref, unable to checkout报错信息
- 文件上传漏洞相关
- Voice data acquisition - real time voice data visualization
- Overview of PCL modules (1.6)
- Basic statement of database operation
- Oracle查看硬解析
- 解决ORCLE-ORA-01122 01110 01210
- 【Liunx】MariaDB/MySQL定时全量备份脚本及数据恢复
- 怎样关闭电脑开机自启动的应用
猜你喜欢

Stylegan paper notes + modify code to try 3D point cloud generation

Ant高级-path和fileset

Open3d library installation, CONDA common instructions, importing open3d times this error solving environment: failed with initial frozen solve Retrying w

pillow的原因ImportError: cannot import name ‘PILLOW_VERSION‘ from ‘PIL‘,如何安装pillow<7.0.0

卸载CUDA11.1

Girl fan wants to find a boyfriend, but it's for

女粉想要找男朋友,竟是为了...

Mail server

线代004

NVIDIA geforce experience login error: the verifier failed to load. Please check your browser settings, such as the advertisement interceptor (solution)
随机推荐
【Liunx】安装MySQL
【Flutter】SharedPreferences使用
Failure of CUDA installation nsight visual studio edition failed
Discussion on a problem
使用 Kmeans聚类实现颜色的分割
Mail server
【英雄哥六月集训】第 26天: 并查集
数据库性能系列之子查询
ctf (hardrce)
Ubuntu及Mysql快速入门教程
NVIDIA geforce experience login error: the verifier failed to load. Please check your browser settings, such as the advertisement interceptor (solution)
Matlab底层源代码实现图像的中值滤波(用于消除图像上一些杂点)
Shell integrated application cases, archiving files, sending messages
Matlab draws the system response under different damping
Word2vec principle and application and article similarity (recommended system method)
Matlab-创建 MATLAB的logo
Pyautogui realizes automatic office -rpa small case
Girl fan wants to find a boyfriend, but it's for
warning package.json: No license field报错
Oracle resizing data files