title: How to implement a singleton with async initialisation and null safety in dart?
body: <p>I need a Singleton for the shared preferences which has async initialisation but also works with null safety. Usually I used the following singleton implementation, but what is the best way to have a singleton which works with null safety?</p>
  <pre><code>class SharedPrefs {
  static SharedPrefs _instance;
  static Future&lt;Null&gt; _mutex;
  
  static Future&lt;SharedPrefs&gt; getInstance() async {
    if (_mutex != null) {
      await _mutex;
    }
    var completer = Completer&lt;Null&gt;();
    _mutex = completer.future;
  
    if (_instance == null) {
      _instance = SharedPrefs();
      await _instance.init();
    }
  
    completer.complete();
    _mutex = null;
  
    return _instance;
  }
  
  SharedPreferences prefs;
  
  SharedPrefs();
  
  Future&lt;SharedPrefs&gt; init() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    return this;
  }
  
  dynamic get(String key) {
    return prefs.getString(key);
  }
  
  Future&lt;bool&gt; put(String key, dynamic value) async {
    return await prefs.setString(key,value);
  }
  }
  </code></pre>