白嫖系列之Flutter-- 单例
网上已经有很多Flutter的单例模式的例子,至于为什么写,那是因为cv都碰到了问题,没办法,自己还得搞一遍,主要还是新版本的判空机制引起的
饿汉式
class Singleton {
// 静态私有成员,没有初始化
static final Singleton _instance = Singleton._();
//公开访问点
factory Singleton.getInstance() => _instance;
// 私有构造函数
Singleton._();
}
懒汉式
class Singleton {
Singleton ._();//设置私有函数
static Singleton? _instance;
static getInstance() {
_instance ??= Singleton._();
return _instance;
}
factory Singleton () => getInstance();
}
预加载模式
为什么有个预加载模式了,针对Flutter中的Feture属性,如果某些数据在app加载的时候需要提前获取,则利用这个
此处以SharedPreferences获取数据为例
class XCacheUtil {
//私有化SharedPreferences
SharedPreferences? _sharedPreferences;
//由于预加载,去掉finial
static XCacheUtil _instance = XCacheUtil._();
//公开访问点
factory XCacheUtil.getInstance() => _instance;
XCacheUtil._(){
// 具体初始化代码
init();
}
//预加载初始化入口,防止相关对象没有初始化
static Future<XCacheUtil> preInit() async {
if (_instance == null) {
var prefs = await SharedPreferences.getInstance();
_instance = XCacheUtil._pre(prefs);
}
return _instance;
}
XCacheUtil._pre(SharedPreferences prefs) {
_sharedPreferences = prefs;
}
//初始化SharedPreferences对象
void init() async {
_sharedPreferences = await SharedPreferences.getInstance();
}
}
扩展
对于使用预加载模式的单例有很多扩展,如FutureBuilder等需要future数据的控件,从而实现通过数据选取控件,后面再对FutureBuilder的使用做具体cv