在Flutter中,是否可以在同步函数内调用异步函数而不将async关键字添加到父函数中?我想像这样调用异步函数:
void getEventsForDay(DateTime day) {
var result = await TaskProvider.getTasksByRangeDate(monthStartMilliseconds, monthEndMilliseconds);
}
由于外部组件不允许,我无法在函数getEventsForDay
中添加async
关键字。但是我仍然需要等待getTasksByRangeDate
返回一些初始数据后才能加载。那么,在不在父函数中添加async
关键字的情况下如何调用异步函数呢?顺便说一句,这是完整代码:
List<TodoTask> getEventsForDay(DateTime day) {
int monthStartMilliseconds = DateTimeUtils.startOfMonthMilliseconds(DateTime.now());
int monthEndMilliseconds = DateTimeUtils.endOfMonthMilliseconds(DateTime.now());
var result = await TaskProvider.getTasksByRangeDate(monthStartMilliseconds, monthEndMilliseconds);
tasks.addAll(result);
buildHashMap(result);
final DateFormat formatter = DateFormat('yyyy-MM-dd');
String dateString = formatter.format(day);
List<TodoTask> dayTodoTask = taskMap[dateString] ?? [];
return dayTodoTask;
}
我已经尝试过像这样使用“then”:
List<TodoTask> getEventsForDay(DateTime day) {
int monthStartMilliseconds = DateTimeUtils.startOfMonthMilliseconds(DateTime.now());
int monthEndMilliseconds = DateTimeUtils.endOfMonthMilliseconds(DateTime.now());
TaskProvider.getTasksByRangeDate(monthStartMilliseconds, monthEndMilliseconds).then((value) => {getTasks(value, day)});
}
List<TodoTask> getTasks(List<TodoTask> tasks, DateTime day) {
tasks.addAll(tasks);
buildHashMap(tasks);
final DateFormat formatter = DateFormat('yyyy-MM-dd');
String dateString = formatter.format(day);
List<TodoTask> dayTodoTask = taskMap[dateString] ?? [];
return dayTodoTask;
}
似乎无法将任务列表返回给外层函数。我尝试了以下方法:
List<TodoTask> getEventsForDay(DateTime day) {
var taskResult;
int monthStartMilliseconds = DateTimeUtils.startOfMonthMilliseconds(DateTime.now());
int monthEndMilliseconds = DateTimeUtils.endOfMonthMilliseconds(DateTime.now());
TaskProvider.getTasksByRangeDate(monthStartMilliseconds, monthEndMilliseconds)
.then((value) => {() => taskResult = getTasks(value, day)});
return taskResult ?? [];
}
List<TodoTask> getTasks(List<TodoTask> tasks, DateTime day) {
tasks.addAll(tasks);
buildHashMap(tasks);
final DateFormat formatter = DateFormat('yyyy-MM-dd');
String dateString = formatter.format(day);
List<TodoTask> dayTodoTask = taskMap[dateString] ?? [];
return dayTodoTask;
}
但是taskResult
的结果总是为空。