How do I initialize a dart class's private property with an async value without initstate?

Viewed 890

Every time this class is instantiated, I wish a call to be made to firebase and the _datapoint given the retrieved value. Otherwise, I have to assign the datapoint in each function in the class (see functionOneExample), and that's just prone to errors. Note: I cannot use initstate as this function is not a widget (I do not need or want a build method). If I could, I would call _getThis in the initstate. Thanks for your help!!

class AsyncInitExample {
  AsyncInitExample(this.enterThis);
  String enterThis;

  String _datapoint;

  _getThis() async {
    var firebaseRetrieved = await //Firebase get this;
    this._datapoint = firebaseRetrieved;
  }

  Future<dynamic> functionOneExample {
    this._datapoint ?? await _getThis();
  }
  // etc. etc. etc.
}
1 Answers

I can recommend making a private constructor together with a static method to fetch all the async values and then use the private constructor to return a object:

class AsyncInitExample {
  AsyncInitExample._(this.enterThis, this._datapoint);
  String enterThis;

  String _datapoint;

  static Future<AsyncInitExample> getInstance(String enterThis) async {
    var firebaseRetrieved = await //Firebase get this;
    return AsyncInitExample._(enterThis, firebaseRetrieved);
  }

  String functionOneExample() => _datapoint;
  
  // etc. etc. etc.
}

By doing it this way, you just need to await the Future from getInstance() and after this, you can access all variables in the class without awaiting.

Related