Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

what is wrong here? (_instance' has not been initialized)

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

   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;
    }
 
}

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading