Search code examples
dartdart-async

Dart: Use Futures to asynchronously fill a static var


I have defined a static var as Map for all instances of my element. If it contains a specific key, it should use the value. If the key is not contains the instance should get the data with a request and save it in the static map, so other instances could use it.

static var data = new Map();

func() {
  if (Elem.data.containsKey(['key']) {
    list = Elem.data['key'];
  }
  else {
    Helper.getData().then((requestedData) {
      list = requestedData;
      Elem.data.addAll({ 'key' : requestedData });
  }
}

The Problem is that all my instances go into the else, since the key is not contained in the Map at the moment the other instances are at the if. So i need them to wait, until the Data is in the Map.


Solution

  • static var data = new Map();
    static Completer _dataCompleter;
    
    Future<bool> func() {
      if(_dataCompleter == null) {
        _dataCompleter = new Completer();
        Helper.getData().then((requestedData) {
          list = requestedData;
          Elem.data.addAll({ 'key' : requestedData });
          _dataCompleter.complete(true);
        })
      } 
      if(_dataCompleter.isCompleted) {
        return new Future.value(true);
      } 
      return _dataCompleter.future;
    }
    

    and call it like

    func().then((success) => /* continue here when `key` in `data` has a value.