Skip to content

Instantly share code, notes, and snippets.

@elbeicktalat
Created November 21, 2021 12:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elbeicktalat/e7403bf6bd88db4dc702b8db92bc864a to your computer and use it in GitHub Desktop.
Save elbeicktalat/e7403bf6bd88db4dc702b8db92bc864a to your computer and use it in GitHub Desktop.
Dart null-safety singleton pattern with parameters.
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.
}
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;
}
@icnahom
Copy link

icnahom commented Dec 2, 2021

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.

@elbeicktalat
Copy link
Author

elbeicktalat commented Jan 6, 2022

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