In Dart, is it possible to pass an argument in a singleton?
The answer can not run on my machine, 29/3/2022
The computer says: “Non-nullable instance field 'id' must be initialized.”
I cannot comment, so write this answer:
Add keyword late
before the member variables will help:
class Peoples {
late int id;
late String name;
static final Peoples _inst = Peoples._internal();
Peoples._internal();
factory Peoples(int id, String name) {
_inst.id = id;
_inst.name = name;
return _inst;
}
}
I'd like to answer showing a way to create a singleton by passing arguments to it and how to "lock" its values after creating it for the first time.
class People {
static final People _inst = People._internal();
People._internal();
factory People(int id, String name) {
assert(!_inst._lock, "it's a singleton that can't re-defined");
_inst.id = id;
_inst.name = name;
_inst._lock = true;
return _inst;
}
int id;
String name;
bool _lock = false;
}
void main() {
var people = People(0, 'Dylan');
try{
print('Instance of = ' + People(0, 'Joe').name);
print('Instance of = ' + People(1, 'Maria').name);
print('Instance of = ' + People(2, 'Ete sech').name);
} finally {
print('Instance of = ' + people.name);
}
}
Sure! You need to pass the arguments to the factory method then you need to update the properties USING the referenced instance.
For example, you had
class Peoples {
late int id;
late String name;
static final Peoples _inst = Peoples._internal();
Peoples._internal();
factory Peoples() {
return _inst;
}
}
If you apply my solution then you have
class Peoples {
late int id;
late String name;
static final Peoples _inst = Peoples._internal();
Peoples._internal();
factory Peoples({int id, String name}) {
_inst.id = id
_inst.name = name
return _inst;
}
}
with this your question should be answered for more info about factory and params visit
https://dart.dev/guides/language/language-tour
Working Example
class Peoples {
late int id;
late String name;
static final Peoples _inst = Peoples._internal();
Peoples._internal();
factory Peoples(int id, String name) {
_inst.id = id;
_inst.name = name;
return _inst;
}
}
void main() {
print("Instance of = " + Peoples(0, "Dylan").name);
print("Instance of = " + Peoples(1, "Joe").name);
print("Instance of = " + Peoples(2, "Maria").name);
}