skip to Main Content
class Logger {
  factory Logger(String name) => Logger._internal(name);

  Logger._internal(this.name);
  final String name;
}

Does this way of writing hold as a so-called singleton pattern?

2

Answers


  1. You should not be making the singleton variables as final cause your goal of making the singleton is to have the same value shared between different class and can be changed from anywhere.

    If your singleton variables are not getting changed than why they are in the singleton, They should be in the constants.

    It should be like this:

    class LoggerSingleton {
      static final LoggerSingleton _singleton = LoggerSingleton._internal();
    
      factory LoggerSingleton() => _singleton;
    
      LoggerSingleton._internal();
    
      String? name;
      // String name = 'Initial value';
    }
    

    And will be used like these, with making a instance or directly with the name:

    void main() {
      LoggerSingleton().name = 'Initial value';
    
      LoggerSingleton logger = LoggerSingleton();
    
      logger.name;
    
      LoggerSingleton().name;
    }
    

    Here if you don’t want to give the value first time before using can just give it at the declaration in the singleton itself that way it don’t need to be nullable.

    Login or Signup to reply.
  2. I use Riverpod Provider objects as lazy singletons, because they are, well, lazy, and they also can be overridden for testing… something difficult to do from a traditional singleton pattern.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search