Wazza
Wazza

Reputation: 1885

Initialize class with asynchronous variable

How can I initialize a class with asynchronous variables so that they are set before the class is used? I have my class currently just calling an async init function but I would have to call that separately to wait for it to finish:

class Storage {

  String imageDirectory;
  String jsonDirectory;
  SharedPreferences instance;
  String uuid;

  init() async {
    imageDirectory = '${(await getApplicationDocumentsDirectory()).path}/image_cache/';
    jsonDirectory = '${(await getApplicationDocumentsDirectory()).path}/json_cache/';
    instance = await SharedPreferences.getInstance();
    uuid = instance.getString("UUID");
  }
}

Is there a better way to do this?

Upvotes: 2

Views: 3737

Answers (1)

Richard Heap
Richard Heap

Reputation: 51682

You might hope that you could have async factory constructors, but they aren't allowed.

So one solution is a static getInstance(), for example:

class Storage {
  static Future<Storage> getInstance() async {
    String docsFolder = (await getApplicationDocumentsDirectory()).path;
    return new Storage(
        docsFolder + '/image_cache/',
        docsFolder + '/json_cache/',
        (await SharedPreferences.getInstance()).getString('UUID'));
  }

  String imageDirectory;
  String jsonDirectory;
  String uuid;

  Storage(this.imageDirectory, this.jsonDirectory, this.uuid);
}

You could pass parameters into getInstance and thus into the constructor, as required. Call the above with:

Storage s = await Storage.getInstance();

Upvotes: 6

Related Questions