I am learning Flutter and I am very desperated. I am writing a small application for my mother that would have been developed in one day in Java. In Flutter I am looking for three days for some problems. I solved some, but now I have no idea what to do. At the moment, I don't like this language.
My application wants to query a database. I have several method calls and the following code is a shortened version of the real code.
Future<List<GarbageCan>> startUseCase(String icsFilePath, int locationId) async {
File icsFile = File(icsFilePath);
List<String> lines = await icsFile.readAsLines();
List<GarbageCan> garbageCans = List();
String date;
List<Appointment> appointments = List();
lines.forEach((line) async {
// Some string operations create the variable month, day, summary and so on.
Appointment appointment = Appointment(year: year,
month: month,
day: day,
locationId: locationId,
garbageCanName: summary);
appointments.add(appointment);
}
});
appointments.forEach((element) async {
print(element);
GarbageCan garbageCan = await _daoManager.findGarbageCanByName(element.garbageCanName);
print("Tonnen\n");
print(garbageCan);
// Here I want to create the objects for the list that should be returned.
});
print("***********************");
// returns the list that is created in the for-each-statement above.
return garbageCans;
}
I want the application wait until the database query in the method findGarbageCanByName() is done. Then the next statements should be executed. But the application executes findGarbageCanByName(), then the return statement and only then the line print(garbageCan);
But I need the application to firstly execute print(garbageCan); for every appointment in the list and then execute the return statement, because I want to create the objects that I want to return in the foreach statement.
This is the method that is called in another class:
Future<GarbageCan> findGarbageCanByName(String garbageCanName) async {
return _garbageCanDao.findGarbageCanByName(garbageCanName);
}
And this method calls that method:
Future<GarbageCan> findGarbageCanByName(String garbageCanName) async {
final db = await database;
String whereString = DatabaseConstants.WHERE_GARBAGE_CAN_NAME;
List<dynamic> whereArguments = [garbageCanName];
List<Map> result = await db.query(
DatabaseConstants.GARBAGE_CAN_TABLE_NAME,
where: whereString,
whereArgs: whereArguments);
return GarbageCan.fromMap(result.first);
}
I am reading about Future, async and awaits for hours and I thought I understood the concept. But now, I am not sure about that. I thought that awaits blocks the operation until the database query is done.
Does anyone know what to do?
Thank you in advance.
Christopher