单例模式确保只创建一个类的实例。我如何在达特建立这个?
当前回答
创建单例
class PermissionSettingService {
static PermissionSettingService _singleton = PermissionSettingService._internal();
factory PermissionSettingService() {
return _singleton;
}
PermissionSettingService._internal();
}
重置单例
// add this function inside the function
void reset() {
_singleton = PermissionSettingService._internal();
}
其他回答
我在dart和之前的Swift上使用这个简单的模式。我喜欢它的简洁和只有一种使用方式。
class Singleton {
static Singleton shared = Singleton._init();
Singleton._init() {
// init work here
}
void doSomething() {
}
}
Singleton.shared.doSomething();
因为我不太喜欢使用new关键字或其他构造函数,比如对单例对象的调用,我更喜欢使用一个名为inst的静态getter:
// the singleton class
class Dao {
// singleton boilerplate
Dao._internal() {}
static final Dao _singleton = new Dao._internal();
static get inst => _singleton;
// business logic
void greet() => print("Hello from singleton");
}
使用示例:
Dao.inst.greet(); // call a method
// Dao x = new Dao(); // compiler error: Method not found: 'Dao'
// verify that there only exists one and only one instance
assert(identical(Dao.inst, Dao.inst));
你可以只使用Constant构造函数。
class Singleton {
const Singleton(); //Constant constructor
void hello() { print('Hello world'); }
}
例子:
Singleton s = const Singleton();
s.hello(); //Hello world
根据文件:
恒定的构造函数 如果类生成永不更改的对象,则可以使这些对象成为编译时常量。为此,定义一个const构造函数,并确保所有实例变量都是final变量。
从Dart 2.13版本开始,就很容易用late关键字了。Late关键字允许我们延迟实例化对象。
作为一个例子,你可以看到:
class LazySingletonExample {
LazySingletonExample._() {
print('instance created.');
}
static late final LazySingletonExample instance = LazySingletonExample._();
}
注意:请记住,当你调用lazy instance field时,它只会被实例化一次。
这也是一种创建Singleton类的方法
class Singleton{
Singleton._();
static final Singleton db = Singleton._();
}
推荐文章
- 使用Enum实现单例(Java)
- 由Jon Skeet撰写的《Singleton》澄清
- 错误地使用父数据小部件。扩展小部件必须放置在flex小部件中
- 颤振给容器圆形边界
- Flutter: RenderBox没有布局
- 颤振插件未安装错误;当运行'扑动医生'时
- 我如何“休眠”Dart程序
- 在Flutter app上检查是否有网络连接
- Flutter and google_sign_in plugin: PlatformException(sign_in_failed, com.google.android.gms.common.api.ApiException: 10:, null)
- 如何在扑动中格式化日期时间
- 在Flutter中Column的子元素之间的空间
- Visual Studio代码- URI的目标不存在" package:flutter/material.dart "
- 如何检查Flutter应用程序是否正在调试中运行?
- 在Flutter中向有状态小部件传递数据
- 未处理异常:ServicesBinding.defaultBinaryMessenger在绑定初始化之前被访问