How I can initialize _instance?
I get "Field '_instance' has not been initialized" Or any other ways to get rid of nullSafety,,,
here is the code:
class ShoppingBasketData{
static late ShoppingBasketData _instance ;
late List<product> _basketItem;
ShoppingBasketData(){
_basketItem =<product>[];
}
List<product> get basketItem => _basketItem;
set basketItem(List<product> value) {
_basketItem = value;
}
static ShoppingBasketData getInstance(){
if (_instance == null){
_instance = ShoppingBasketData();
}
return _instance;
}
}
CodePudding user response:
What is wrong is that you declared _instance
to be late
. What that means is that you as a developer promise to initialize it before you access it. If you break that promise, you get an exception.
It seems that you want null
to be a valid value, so what you need to do is make it nullable:
static ShoppingBasketData? _instance
You may also want to look into How do you build a Singleton in Dart? so you don't have to reinvent the wheel, and you may want to look into Flutter state management, because singleton is probably the worst of all options.