首页 > 解决方案 > 如何在飞镖中添加单例?

问题描述

我对颤振很陌生,我想在我的颤振应用程序中添加单例。我使用共享首选项来保存我的私钥和公钥,但我也想在启动应用程序时从中获取此信息

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;
  }
}

标签: flutterdart

解决方案


您不需要工厂构造函数,因为您可以直接使用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;
}

推荐阅读