Created
November 21, 2021 12:42
-
-
Save elbeicktalat/e7403bf6bd88db4dc702b8db92bc864a to your computer and use it in GitHub Desktop.
Dart null-safety singleton pattern with parameters.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void main() { | |
Person personA = Person(); | |
Person personB = Person(); | |
print(personA); | |
print(personB); | |
print(identical(personA, personB)); // if this return `true`, that mains this class is singleton. | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Person { | |
static final Person _instance = Person._internal(); | |
Person._internal(); | |
factory Person({ | |
String? name, | |
String? lastName, | |
int? age, | |
}) { | |
_instance.name = name; | |
_instance.lastName = lastName; | |
_instance.age = age; | |
return _instance; | |
} | |
String? name; | |
String? lastName; | |
int? age; | |
} |
Hi @icnahom I'm sorry for the delay answer,
You are absolutely right.
For simplicity I think if you want instance variables as non-null, remove ?
mark, it'll ask for the constructer, to solve that you should declare variables with late
keyword for later assignment.
Note: For each instance you should initialize variables other way you'll got an initialization error.
Conclusion Using late
keyword is more helpful if your constructer has no optional parameters.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice trick, but you are going to loose the variables when trying to access Person() again. It will set will set them back to null, so you will have to check for null before changing the variable of the instance.