簡體   English   中英

如何在dart中添加Singleton?

[英]How to add Singleton in dart?

我對 flutter 很陌生,我想在我的 flutter 應用程序中添加 singleton。 我使用共享首選項來保存我的私鑰和公鑰,但我也想在啟動應用程序時從中獲取此信息

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 屏幕。 我需要在 Singleton 中添加我的 pubKey、privateKey、UId 和 userName 數據。 我用工廠構造復制了隨機的 singleton 代碼。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM