I have this class which takes some parameters by using the factory constructor, if instance is null, a new object will be created; if it's not null, the value of instance will be returned so we always receive the same object all the time (Singleton). This is how I used the singleton pattern before enabling null-safety features of dart.
class GuestUser extends User {
static GeustUser _instance;
factory GuestUser(
{required String firstName,
required String lastName,
required String email,
required Address address,
required PaymentInfo paymentInfo}) {
if (_instance == null) {
_instance =
GuestUser._(firstName, lastName, email, address, paymentInfo);
}
return _instance;
}
Now with null-safety enabled, I get this error:
The non-nullable variable '_instance' must be initialized.
Try adding an initializer expression.
Also if (_instance == null)
is not needed anymore.
If I define the _instance
like this: static late final GuestUser _instance;
then I cannot use the if (_instance == null)
to only create the _instance when needed. so I have to remove the if statement and create a new instance every time the factory constructor is called.
How can I solve this issue and create a singleton class with null-safety enabled?
I have this solution in mind to keep track of the instance with a boolean variable:
static late final GeustUser _instance;
static bool _isInstanceCreated = false;
factory GuestUser(
{required String firstName,
required String lastName,
required String email,
required Address address,
required PaymentInfo paymentInfo}) {
if (_isInstanceCreated == false) {
_instance =
GuestUser._(firstName, lastName, email, address, paymentInfo);
}
_isInsanceCreated = true;
return _instance;
}
But I want to know whether there is a way to do this without defining new variable and by using the features of the null-safety