async is snowballing to callers, can’t make constructor async

I have a function loadData that loads some text from a file:

Future<String> loadAsset() async {
  return await rootBundle.loadString('assets/data/entities.json');
}

The loadString method is from Flutter SDK, and is asynchronous.

The loadAsset method is then called in another method, that must me marked as async, since loadAsset is async and I need to use await:

Future<List<Entity>> loadEntities() async {
  String jsonData = await loadAsset();
  return parseData(jsonData);
}

The parseData method is not async, it receives a String, parse it, and return a list of objects:

List<Entity> parseData(String jsonString) {
  ...
}

But since loadEntities must be marked with async, this requires that it returns a Future, but in practice, it's not a Future because since I use await, it awaits for the loadAsset method to finish, then call the parseData funcion using the result.

This easily turns into a snowball of async call, because every method that uses loadEntities must be marked as async too.

Also, I can't use loadEntities in a class constructor, because the constructor should be marked as async, which is not allowed in Dart.

Am I using the async/await pattern in Dart wrong? How could I use the loadEntities method in a class constructor?



Read more here: https://stackoverflow.com/questions/49537996/async-is-snowballing-to-callers-cant-make-constructor-async

Content Attribution

This content was originally published by rbasniak at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: