1

I was using flutter 2 and updated to flutter 3. now I have an error in my singleton class

my class is that work fine on flutter 2 is:

class FBServices {

  FBServices._privateConstructor();
  static final _instance = FBServices._privateConstructor();

  factory FBServices(){
    return _instance;
  }
}

Am using Factory but all I want is to have a one instance of that class all over my app.

yassine yass
  • 43
  • 1
  • 7
  • 2
    Your code is already a singleton since `static` and global variables in Dart are always lazy evaluated. So your `_instance` will automatically first call `FBServices._privateConstructor()` when something tries to access that variable the first time and then later requests will return that exact instance. You can test that by trying to print something in your `_privateConstructor()` constructor. Your code should therefore already work, so I want to ask what error you are getting? – julemand101 Jun 06 '22 at 19:06
  • You could use this moment to move to a better solution. [Singleton is an anti-pattern](https://stackoverflow.com/questions/12755539/why-is-singleton-considered-an-anti-pattern) anyway. – nvoigt Jun 06 '22 at 19:14

1 Answers1

4

You can achieve a singleton by the code:

class FBServices {

    FBServices._privateConstructor();
    static FBServices? _instance;

    factory FBServices() => _instance ??= FBServices._privateConstructor();
}

The trick is in the factory; ??= this is equivalent to the code:

if(_instance == null)
    _instance ??= FBServices._privateConstructor();
return _instance;

By the code above, the constructor FBServices._privateConstructor() will be called once in your app lifecycle

Abdallah A. Odeh
  • 1,494
  • 6
  • 17
  • even my code is working fine, the problem was with android studio that for some reason showed me that "FBServices._privateConstructor();" is incorrect. i just had to reboot the pc and rebuild the program and the error is no longer there. – yassine yass Jun 08 '22 at 10:46
  • Yeah, android studio does that from time to time, you will probably notice it because it will show that `List` or `Future` method is incorrect! – Abdallah A. Odeh Jun 08 '22 at 12:34