1

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;
    }
 
}
New
  • 13
  • 4

1 Answers1

0

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.

nvoigt
  • 75,013
  • 26
  • 93
  • 142
  • thanks I did So, but its another error : """ A value of type 'ShoppingBasketData?' can't be returned from the method 'getInstance' because it has a return type of 'ShoppingBasketData'."" what else I can do? – New Nov 04 '21 at 15:13
  • You could use a `!` since you know it's not null, `return _instance!;` but you should really look into alternatives to your singleton alltogether. Or at least a better Singleton pattern. See the links I added. – nvoigt Nov 04 '21 at 15:17
  • Thannnnnnksssss!!!! It solved it!!! – New Nov 04 '21 at 15:26