我在哪里使用await返回Future dart / flutter ?



我正在调用一个future,我正在返回一个_InternalLinkedHashMap,但我正在获得错误类型

'Future<dynamic>' is not a subtype of type 'Map<DateTime, List<Event>>'

我很困惑,因为我在等待未来,当我打印出来的时候,我得到了看起来正确的地图

// Gets the Future
FutureCalendarEvents datasource = const FutureCalendarEvents(); //Future Call

然后放入一个函数并等待它

Future<Map<DateTime, String>> myDates() async { //is My Dates a 'Future<dynamic>' ???
final List<CalendarDetails> myDatesFuture = await  datasource.getCalendarFuture();    

try {
final Map<DateTime, String> _kEventSource = { 
for (var item in myDatesFuture) 
DateTime.parse(item.calendarTableTime) : 
[Event(item.calendarEventName)]
};
print(_kEventSource.runtimeType); //_InternalLinkedHashMap<DateTime, String>
return _kEventSource;
} catch (e) {
print("ERROR MESSAGE → → → " + e.toString() );
}
}

这是我得到的错误

The following _TypeError was thrown building LayoutBuilder:
type 'Future<dynamic>' is not a subtype of type 'Map<DateTime, List<Event>>'

Map返回到

final awaitedMyDate = await myDates(); // Must be in a function??
// Takes my events
final kEvents = LinkedHashMap<DateTime, String>(
equals: isSameDay,
hashCode: getHashCode,
)..addAll(myDates());

然后这里是传递kEvents到

的地方
kSources ()  async {
final Map<DateTime, List<Event>> awaitedMyDate = await myDates();
return awaitedMyDate;
}
final kEvents = LinkedHashMap<DateTime, List<Event>>(
equals: isSameDay,
hashCode: getHashCode,
)..addAll(kSources());

您应该将myDates更改为未来类型,然后等待:

Future <Map<DateTime, String>> myDates() async {

然后

final awaitedMyDate = await myDates();
final kEvents = LinkedHashMap<DateTime, List<Event>>(
equals: isSameDay,
hashCode: getHashCode,
)..addAll(awaitedMyDate);
myDates() async { //is My Dates a 'Future<dynamic>' ???

是的,它是。你从来没有给它一个类型,所以编译器尽其所能。它是async,所以它必须返回一个future,但是你没有指定是什么类型,所以它是Future<dynamic>

如果你想让它返回一个Future<Map<DateTime, List<Event>>>,那么你必须这样做:

Future<Map<DateTime, List<Event>>> myDates() async {

最新更新