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?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…