来自面向对象的编程背景,我计划制作一个专用的Settings类来存储有关该应用程序的某些基本数据。
我计划首先使用SharedPreferences和LocalStorage保存应用程序的主题。
但是,SharedPreferences.getInstance()似乎总是返回null。
我尝试过简单地运行,以调试模式运行,有一个单独的异步方法来加载SharedPreferences并返回一个使用.then()展开的Future。我似乎无法弄清楚为什么我总是从我编写的AppSettings.getInstance()方法的SharedPreferences.getInstance()中得到空值。
import 'package:shared_preferences/shared_preferences.dart';
import 'package:localstorage/localstorage.dart';
import 'package:flutter/material.dart';
class AppSettings {
// Singleton Instance
static AppSettings _appSettings;
// For First Launch Recognition
bool _initialize;
// Storage instances for persistent settings storage
static SharedPreferences _prefs;
static LocalStorage _dayColors = new LocalStorage('_dayColors');
static LocalStorage _nightColors = new LocalStorage('_nightColors');
// App Settings
bool _nightTheme;
Color _dayBgColor;
Color _primaryDayColor;
Color _secondaryDayColor;
Color _accentDayColor;
Color _nightBgColor;
Color _primaryNightColor;
Color _secondaryNightColor;
Color _accentNightColor;
static AppSettings getInstance() {
SharedPreferences.getInstance().then((prefs) => _prefs = prefs);
_appSettings ??= AppSettings._();
return _appSettings;
}
///
/// Initialize App Settings
///
AppSettings._() {
_checkIfFirstLaunch();
if (_initialize) {
_loadDefaultSettings();
_saveSettings();
} else {
_loadSettings();
}
}
_checkIfFirstLaunch() {
try {
_initialize = _prefs.getBool("_initialize");
} catch (e) {
_initialize = true;
}
}
_loadSettings() {
_nightTheme = _prefs.getBool("_nightTheme");
_dayColors.ready.then((_) => _loadDayColors());
_nightColors.ready.then((_) => _loadNightColors());
}
_loadDefaultSettings() {
_nightTheme = false;
_dayBgColor = Colors.white;
_primaryDayColor = Colors.blue;
_secondaryDayColor = Colors.lightBlue;
_accentDayColor = Colors.blueAccent;
_nightBgColor = Colors.black54;
_primaryNightColor = Colors.green;
_secondaryNightColor = Colors.lightGreen;
_accentNightColor = Colors.amber;
}
_saveSettings() {
_prefs.setBool("_nightTheme", _nightTheme);
_dayColors.ready.then((_) => _saveDayColors());
_nightColors.ready.then((_) => _saveNightColors());
}
}
SharedPreferences.getInstance()应该返回SharedPreferences单例实例。它一直返回null。
答案 0 :(得分:2)
您的函数异步,并且您的回调(then
)在返回getInstance()
之后执行。您必须更改函数以使用await
并获取SharedPreferences.getInstance()
的值,而不要使用SharedPreferences.getInstance().then(...)
查看文档:{{3}}
SharedPreferences.getInstance()的实现。
static Future<SharedPreferences> getInstance() async {
if (_instance == null) {
final Map<String, Object> preferencesMap =
await _getSharedPreferencesMap();
_instance = SharedPreferences._(preferencesMap);
}
return _instance;
}
答案 1 :(得分:0)
以下是基于Augusto答案的代码:
static Future<AppSettings> getInstance() async {
_prefs = await SharedPreferences.getInstance();
_appSettings ??= AppSettings._();
return _appSettings;
}