Flutter:无法将 `Future<Map<DateTime, dynamic>>` 赋值给 `Map<DateTime, dynamic>`。

时间:2021-08-12 04:14:49

标签: flutter dart google-cloud-firestore

我有一个函数从 Firestore 获取数据并将其添加到 Map 中。当我尝试使用它时,出现了这个错误:“参数类型'Future<Map<DateTime, dynamic>>'不能分配给参数类型'Map<DateTime, dynamic>'。”

代码如下:

final Map<DateTime, dynamic> testMap = {};

Future<Map<DateTime, dynamic>> getEventsList() async {
  var data = await FirebaseFirestore.instance.collection('events').get();

  for (int i = 0; i < data.docs.length; i++) {
    var time = (data.docs[i]['date'] as Timestamp).toDate();
    var title = Event(data.docs[i]['title']);
    testMap[time] = title;
  }

  print(testMap);
  return testMap;
}

final kEvents = LinkedHashMap(
  equals: isSameDay,
  hashCode: getHashCode,
)..addAll(getEventsList()); <-- 错误在这里

1 个答案:

答案 0 :(得分:1)

你需要 await 它:

final kEvents = LinkedHashMap(
  equals: isSameDay,
  hashCode: getHashCode,
)..addAll(await getEventsList());

然而,你需要在一个 异步上下文 中,例如:

void _addToMap() async {
  final kEvents = LinkedHashMap(
    equals: isSameDay,
    hashCode: getHashCode,
  )..addAll(await getEventsList());
}