每当我们必须使用共享首选项时,我们都必须创建它的一个实例。
在 flutter 中创建共享首选项的实例是异步的;
final prefs = await SharedPreferences.getInstance();
每当我们需要像上面那样使用它时,我们都必须创建它的实例。
有没有一种方法可以创建共享首选项的单个实例,该实例可供整个项目使用,而我们不必在 Flutter 中一次又一次地创建其实例?
创建
SharedPreference
的单例类:
import 'dart:async' show Future;
import 'package:shared_preferences/shared_preferences.dart';
class PreferenceUtils {
static Future<SharedPreferences> get _instance async => _prefsInstance ??= await SharedPreferences.getInstance();
static SharedPreferences _prefsInstance;
// call this method from iniState() function of mainApp().
static Future<SharedPreferences> init() async {
_prefsInstance = await _instance;
return _prefsInstance;
}
static String getString(String key, [String defValue]) {
return _prefsInstance.getString(key) ?? defValue ?? "";
}
static Future<bool> setString(String key, String value) async {
var prefs = await _instance;
return prefs?.setString(key, value) ?? Future.value(false);
}
}
void main() async {
// Required for async calls in `main`
WidgetsFlutterBinding.ensureInitialized();
// Initialize PreferenceUtils instance.
await PreferenceUtils.init();
runApp(MyApp());
}
PreferenceUtils.setString(AppConstants.USER_ID, "");
String userId = PreferenceUtils.getString(AppConstants.USER_ID);
更多:https://dev.to/lucianojung/flutter-singelton-pattern-1a38
SharedPreferences.getInstance()
已返回单例。它从磁盘读取一次,后续调用仅返回已解决的未来。这样,只需将 await SharedPreferences.getInstance();
返回的对象存储在全局可访问的地方即可。
查看下面的源代码。它在应用程序的生命周期内创建一次静态
_completer
。
/// Loads and parses the [SharedPreferences] for this app from disk.
///
/// Because this is reading from disk, it shouldn't be awaited in
/// performance-sensitive blocks.
static Future<SharedPreferences> getInstance() async {
if (_completer == null) {
final Completer<SharedPreferences> completer = Completer<SharedPreferences>();
try {
final Map<String, Object> preferencesMap = await _getSharedPreferencesMap();
completer.complete(SharedPreferences._(preferencesMap));
} on Exception catch (e) {
// If there's an error, explicitly return the future with an error.
// then set the completer to null so we can retry.
completer.completeError(e);
final Future<SharedPreferences> sharedPrefsFuture = completer.future;
_completer = null;
return sharedPrefsFuture;
}
_completer = completer;
}
return _completer!.future;
}
除了单独创建单例之外,您还可以这样做。您可以使用全局定义的方法创建一个 dart 文件。我所说的全球范围是指课堂之外。
late SharedPreferences prefs;
void initiateSharedPreferences()
{
prefs = await SharedPreferences.getInstance();
}
从 main.dart 调用此方法来启动首选项。现在 var pref 全局可用。现在无论你在哪里使用 prefs,你只需要导入这个 dart 文件,就可以正常使用 prefs 了。
使用简单的 Dart 服务定位器 get_it。当您还必须使用除 SharedPreferences 之外的全局对象时,您会遇到很多这样的情况。 第一步是添加 get_it 的依赖项。只需转到链接, 并按照以下步骤设置共享首选项。
您的共享首选项将是
import 'package:flutter/cupertino.dart';
import 'package:shared_preferences/shared_preferences.dart';
class SharedPrefs extends ChangeNotifier {
SharedPreferences? _prefsInstance;
SharedPrefs() {
_init();
}
Future<void> _init() async {
_prefsInstance = await SharedPreferences.getInstance();
getIt.signalReady(this);
}
bool getBool(String key, [bool elseValue = false]) {
return _prefsInstance?.getBool(key) ?? elseValue;
}
Future<bool> setBool(String key, bool value) async {
return _prefsInstance?.setBool(key, value) ?? Future.value(false);
}
}
在
main.dart
import 'package:flutter/material.dart';
import 'package:get_it/get_it.dart';
import 'package:yourpackage/shared_prefs.dart';
import 'app.dart';
GetIt getIt = GetIt.instance;
void main() {
WidgetsFlutterBinding.ensureInitialized();
getIt.registerSingleton(SharedPrefs(), signalsReady: true);
runApp(const App());
}
任何需要共享首选项的地方,您都可以称之为
final authenticated = getIt<SharedPrefs>().getBool('key_auth');
import 'package:shared_preferences/shared_preferences.dart';
class SharedPreference {
static SharedPreferences? prefs;
static String token = 'token';
static addStringToSF(String key, String value) async {
prefs = await SharedPreferences.getInstance();
prefs!.setString(key, value);
}
static addIntToSF(String key, int value) async {
prefs = await SharedPreferences.getInstance();
prefs!.setInt(key, value);
}
static addBoolToSF(String key, bool value) async {
prefs = await SharedPreferences.getInstance();
prefs!.setBool(key, value);
}
static Future<String> getStringValuesSF(String key) async {
prefs = await SharedPreferences.getInstance();
String? getString = prefs!.getString(key);
return (getString != null) ? getString : '';
}
static Future<int> getIntValuesSF(String key) async {
prefs = await SharedPreferences.getInstance();
int? getString = prefs!.getInt(key);
return (getString != null) ? getString : 0;
}
static Future<bool> getBoolValuesSF(String key) async {
prefs = await SharedPreferences.getInstance();
bool? getbool = prefs!.getBool(key);
return (getbool != null) ? getbool : false;
}
static Future<bool> removeValues(String key) async {
prefs = await SharedPreferences.getInstance();
return await prefs!.remove(key);
}
static dynamic containsKey(String key) async {
prefs = await SharedPreferences.getInstance();
return prefs!.get(key);
}
static Future<bool> removePrefs() async {
prefs = await SharedPreferences.getInstance();
return await prefs!.clear();
}
}
SharedPreference.addStringToSF(
SharedPreference.token, logindata11.token.toString());
class Constant {
static String token = '';
}
Constant.token =
await SharedPreference.getStringValuesSF(SharedPreference.token);