flutter - 如何在飞镖中添加单例?
问题描述
我对颤振很陌生,我想在我的颤振应用程序中添加单例。我使用共享首选项来保存我的私钥和公钥,但我也想在启动应用程序时从中获取此信息
try {
userPubKey = getPublicKey() as String;
userPrivateKey = getPrivateKey() as String;
} catch (e) {
}
if (userPrivateKey == "null" || userPubKey == "null") {
var crypter = RsaCrypt();
var pubKey = crypter.randPubKey;
var privKey = crypter.randPrivKey;
String pubKeyString = crypter.encodeKeyToString(pubKey);
String privKeyString = crypter.encodeKeyToString(privKey);
setPublicKey(pubKeyString);
setPrivateKey(privKeyString);
userPubKey = pubKeyString;
userPrivateKey = privKeyString;
}
这是我的单例屏幕。我需要在 Singleton 中添加我的 pubKey、privateKey、UId 和 userName 数据。我用工厂构造复制了随机单例代码。
class Singleton {
Singleton.privateConstructor();
static final Singleton instance = Singleton.privateConstructor();
factory Singleton() {
return instance;
}
String pubKey;
String privateKey;
String userName;
String userID;
setPubKey(String key){
this.pubKey = key;
}
String getPubKey(){
return this.pubKey;
}
}
解决方案
您不需要工厂构造函数,因为您可以直接使用instance
变量 being static
。这是你如何做到的。
class Singleton {
Singleton._();
static final Singleton instance = Singleton._();
String pubKey;
String privateKey;
String userName;
String userID;
void setPubKey(String key) => pubKey = key;
String getPubKey() => pubKey;
}
void main() {
var instance = Singleton.instance;
}
推荐阅读
- python - Python - 数据帧中第 2、第 3、第 n 大的 idxmax
- wcf - 如何在 WSDL 中为 WCF 服务设置 EndpointReference?
- node-red - 如何创建节点红色流以与 fiware-orion-context-broker 建立连接
- mysql - 从多个表中获取数据并对结果应用算术运算
- composer-php - Friendsofsymfony/ckeditor-bundle 与 sebastian/exporter 冲突
- javascript - JS:音频在首次加载时播放,但不在页面刷新时播放
- ssl-certificate - 如何在 selenium chrome webdriver 中接受 SSL 证书
- javascript - 选择选项时更改必填字段形式
- odoo - 更改/修改不影响 odoo UI
- postgresql - 如何在 .innerJoin() 中使用变量?