0

i'm pretty new to flutter and i want to add singleton in my flutter app. I used shared preferences to save my private and public key, but also i want to take this info from it when i launch app

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

Here is my singleton screen. I need to add my pubKey, privateKey, UId and userName data in Singleton. I copied random singleton code with factory construct.

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;
  }
}
  • What's the benefit of using `factory` constructor when you already have a named `privateConstructor` which itself isn't private. Second, I didn't understand your question very well. – iDecode Mar 30 '21 at 11:46
  • to be fair, i just copied random code with factory contructor. I'm new to programming also, so i'm trying to find where i must put my String pubKey; String privateKey; String userName; String userID; in this singleton constructor –  Mar 30 '21 at 11:50
  • Your implementation is almost correct. The only thing you should do is to make privateConstructor really private, but prepending "_". See here for example: https://stackoverflow.com/questions/12649573/how-do-you-build-a-singleton-in-dart – Alex Radzishevsky Mar 30 '21 at 12:04

1 Answers1

0

You don't need factory constructor as you can directly use instance variable being static. Here's how you do it.

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;
}
iDecode
  • 22,623
  • 19
  • 99
  • 186
  • i just need to add this in my singleton.dart file and call it in my main screen? –  Mar 30 '21 at 12:24
  • You don't need `main` function here, I just showed you how you'll access the single instance of your class using `Singleton.instance`. Replace the rest of the code (without `main`) and use it wherever you were using it in the first place. – iDecode Mar 30 '21 at 12:30