为什么我会收到“类型‘List<dynamic>’不是类型‘List<DocumentReference<Map<String, dynamic>>>’的子类型”错误?

问题描述 投票:0回答:1

我在 flutter 中运行单元测试,出现错误: 类型“List”不是类型“List>>”

的子类型

相关代码片段如下,我试图从 firebase 读取数据。

 factory TimerSessionModel.fromSnapshot(
      DocumentSnapshot<Map<String, dynamic>> snapshot) {
    final data = snapshot.data()!;
    return TimerSessionModel(
      selfRef: snapshot.reference,
      activeExecutionRef: data['activeExecutionRef'],
      autoStartNextTimer: data['autoStartNextTimer'] as bool,
      ownerRef: data['ownerRef'],
      timerRefs: data['timerRefs'],
      title: data['title'] as String,
    );
  }

这里timerRefs是一个文档引用列表,问题所指向的地方。

我尝试运行单元测试并给出了如上所述的错误

flutter firebase google-cloud-firestore
1个回答
0
投票

您需要将列表类型转换为 >>。

    factory TimerSessionModel.fromSnapshot(
  DocumentSnapshot<Map<String, dynamic>> snapshot) {
  final data = snapshot.data()!;
  // Convert List<dynamic> to List<DocumentReference<Map<String, dynamic>>>
  List<DocumentReference<Map<String, dynamic>>> timerRefs = 
    (data['timerRefs'] as List<dynamic>)
    .map((ref) => ref as DocumentReference<Map<String, dynamic>>)
    .toList();

  return TimerSessionModel(
    selfRef: snapshot.reference,
    activeExecutionRef: data['activeExecutionRef'],
    autoStartNextTimer: data['autoStartNextTimer'] as bool,
    ownerRef: data['ownerRef'],
    timerRefs: timerRefs,
    title: data['title'] as String,
  );
}
© www.soinside.com 2019 - 2024. All rights reserved.