I've applied the singleton pattern as in this issue and tried to accept a parameter using the method in this issue But it gives me the error :
Non-nullable instance field 'id' must be initialized. Try adding an initializer expression, or add a field initializer in this constructor, or mark it 'late'
so where is the issue ? , here is my code
static final Singleton _inst = Singleton._internal();
Singleton._internal() {
// some logic
}
factory Singleton({required int id}) {
_inst.id = id;
return _inst;
}
CodePudding user response:
Without your full code I am going to assume that your full Singleton
class looks something like this:
class Singleton {
int id;
static final Singleton _inst = Singleton._internal();
Singleton._internal() {
// some logic
}
factory Singleton({required int id}) {
_inst.id = id;
return _inst;
}
}
The thing is that since nullsafety you can't declare a non-nullable variable without assigning its value or mark it as late
(just as said in your error message).
So what you should do is simply declare id
like this:
class Singleton {
late int id;
// ...
}
Try the full sample on DartPad
CodePudding user response:
In your People or Singlton class you have defined a field named id which is neither nullable nor initialized that is why you are getting this error. Just make your field nullable or assign some value to it to initialize. Like below
To make it nullable
int? id;
To initialize
int id = "";