How to add Singleton in dart? - flutter

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

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

Related

in return only show Instance of 'User' User is a class

I want this code to convert a csv file to a list, and then convert it to json, for the firebase database, instead of list this code return array it shows an instance of class, like this :
[Instance of 'User', Instance of 'User', Instance of 'User']
void main() {
var users= "username, email, phone \n ctavia,octavia#gmail.com, 099-83-44 \n lark, clark#gmail.com, 054-83-23 \n aven, raven#gmail.com, 784-44-98";
var data = csvToUsersList(users);
print(data);
}
class User {
String username;
String email;
String phone;
User(this.username, this.email, this.phone);
}
List<User> csvToUsersList(String data) {
List<User> users = [];
List<String> userin= data.split("\n");
for (int i = 1; i < userin.length; i++) {
List<String> user = userin[i].split(",");
users.add(User(user[0], user[1], user[2]));
}
return users;
}
That seems correct. If you print something like data.first.username, you should get the name of the first User.
Instance of User just means, that this is an Object of Type User.

class object and property variation in dart

so i recently started learning dart and I've found something kinda interesting.
why do we use constructors and getters/setters when we can achieve same results without them? (atleast when used for basic things).
class v1{
var name;
int age;
v1(this.name, this.age);
info(){
print("my name is $name and i am $age");
}
}
class v2{
var name = "bash";
int age = 100;
info(){
print("my name is $name and i am $age");
}
}
class v3{
var namee;
int agee;
String get name => namee;
int get age => agee;
set name(String name) => this.namee = name;
set age(int age) => this.agee = age;
info(){
print("my name is $name and i am $age");
}
}
void main(){
var x = v1("bash", 100);
x.info(); //my name is bash am i am 100
var z = v2();
var Z = v2();
Z.name = "vert";
Z.age = 20;
z.info(); //my name is bash and i am 100
Z.info(); //my name is vert and i am 100
var y = v3();
y.name = "rizz";
y.age = 40;
y.info(); //my name is rizz and i am 40
}
Here's a more correct version of your class:
class User {
final bool _isMale;
String _name;
int _age;
User(this._isMale, this._name, this._age);
bool isMale => _isMale;
String get name => _name;
int get age => _age;
set name(String name) {
// Sometimes you may want to update other properties here.
// For example:
// _isUpdated = true;
_name = name;
}
set age(int age) {
_age = age;
}
void info() {
print("my name is $name and i am $age");
}
}
Constructors are useful when you want to assign initial values to the class fields. They are essential if you need to assign final fields, as they are assignable only on class initialization (see _isMale field).
Setters are useful when you want to update other fields along with the field that's being modified.
Getters protect the internal state from being modified outside. In this example, nobody can change _isMale field.
You don't need to use getters and setters unless you have to.
You use getters and setters if you need to store the data in a private field, or if you want to modify it when saving or returning the value.
class Abc {
String _field;
String _otherField;
String anotherField; // No getters and setters required for this.
String get field => _field;
set field(String field) => _field = field;
String get otherField => "The value of otherField is: " + _otherField;
set otherField(String otherField) => _otherField = "[String] " + otherField;
}
As for constructors, you use them to initialize the object with custom values. When you need to work with immutable objects (which use final variables), you'll have to use constructors to set their initial value. You can also modify the incoming value according to your need before storing it,
class Def {
final field; // Dart generates getters for this field, but it's value can't be modified once the object is instantiated.
final _otherField; // No getters for this.
Def(String field, String otherField) {
this.field = "[String] $field"
this._otherField = "[String] $otherField"
}
String describeMe() {
return "[Def]: field: $field, _otherField: $_otherField"
}
}

How to pass String to constructor from a map

I'm trying to create an Athlet Object from a DocumentSnapshot. In this DocumentSnapshot I have stored a map, that holds the values(i.E. "upperbody": 0), to this athletes favourite Categorys. But for the AthleteObject I only need the key, of the category with the highest Value.
This should work, but I get the following error. And I dont' know how to rewrite this for it to not complain.
The instance member 'getFavCategory' can't be accessed in an initializer. (Documentation) Try replacing the reference to the instance member with a different expression
Athlete.fromJSON(DocumentSnapshot parsedJSON):
_name = parsedJSON["name"],
_rank = parsedJSON['rank'],
_xp = parsedJSON['xp'],
_foot = parsedJSON['foot'],
_position = parsedJSON['position'],
_statsDate = parsedJSON['statsDate'],
_challengeCount = parsedJSON['challengeCount'],
_workoutCount = parsedJSON['workoutCount'],
_favCategory = getFavCategory(parsedJSON['favCategory']),
_shotsTaken = parsedJSON['shotsTaken'],
_shotsMade = parsedJSON['shotsMade'],
_passesTaken = parsedJSON['passesTaken'],
_passesMade = parsedJSON['passesMade'];
String getFavCategory(Map<String, dynamic> map){
String favCat;
int maxVal;
map.forEach((key, value) {
if(maxVal == null || value > maxVal){
maxVal = value;
favCat = key;
}
});
return favCat;
}
Your definition of getFavCategory states that it has to be called on an initialized instance of your Athlete class (which is not a case for your constructor).
The fastest you can do is simply turn your getFavCategory function in to static (since you are not using any class variables inside):
static String getFavCategory(Map<String, dynamic> map){
String favCat;
int maxVal;
map.forEach((key, value) {
if(maxVal == null || value > maxVal){
maxVal = value;
favCat = key;
}
});
return favCat;
}

Access member by another member in a Class List Flutter

I'm trying to find the name using the id in modelList from the example below.
class Example{
List<Abc> modelList = [
Abc(1, "John"),
Abc(2, "Christine"),
Abc(3, "Steven"),
Abc(4, "Others"),
];
myFun(){
int idToFind = 4;
String foundString = // Some iterable function??
}
}
class Abc{
int id;
String name;
Abc(this.id, this.name);
}
String foundString = modelList.firstWhere((abc) => abc.id == idToFind).name;

Mapping CSV data in flutter

Auto-complete search list
How to parse csv data instead of json data as mentioned in this article. I am new to csv and I have trouble mappping csv data to a model list. I need to pass the csv list to autocomplete field in another package plz help me in mapping it to the model.
class Players {
String keyword;
int id;
String autocompleteterm;
String country;
Players({
this.keyword,
this.id,
this.autocompleteterm,
this.country
});
factory Players.fromJson(Map<String, dynamic> parsedJson) {
return Players(
keyword: parsedJson['keyword'] as String,
id: parsedJson['id'],
autocompleteterm: parsedJson['autocompleteTerm'] as String,
country: parsedJson['country'] as String
);
}
}
class PlayersViewModel {
static List<Players> players;
static Future loadPlayers() async {
try {
players = new List<Players>();
String jsonString = await rootBundle.loadString('assets/players.json');
Map parsedJson = json.decode(jsonString);
var categoryJson = parsedJson['players'] as List;
for (int i = 0; i < categoryJson.length; i++) {
players.add(new Players.fromJson(categoryJson[i]));
}
} catch (e) {
print(e);
}
}