You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter使用fromMap构造函数时遇List类型不匹配错误求助

问题:Firestore数据转换错误:List无法转为List

我正在开发一款基础聊天应用,需要从Firebase Firestore的chatrooms集合中获取所有可用聊天室,用来展示登录用户的所有聊天室,但在数据转换阶段遇到了错误:

type 'List' is not a subtype of type 'List'

我的代码

ChatRoomModel类

class ChatRoomModel {
  String chatroomid;
  List<String> participants;
  ChatRoomModel({required this.chatroomid, required this.participants});

  factory ChatRoomModel.fromMap(Map<String, dynamic> map) {
    return ChatRoomModel(
        chatroomid: map['chatroomid'],
        participants:map['participants']);
  }

  Map<String, dynamic> toMap() {
    return {
      "chatroomid": chatroomid,
      "participants": participants,
    };
  }
}

获取数据的方法

Future<void> fetchData() async {
    QuerySnapshot qsnapshot = await FirebaseFirestore.instance.collection(
        "chatrooms").get();
    final int num_of_rooms = qsnapshot.docs.length;
    print(num_of_rooms);
    if (num_of_rooms > 0) {
      final alldata=qsnapshot.docs.map((e) => e).toList();
      List<ChatRoomModel> templist=[];
      for(var x in alldata)
        {
          templist.add(ChatRoomModel.fromMap(x.data() as Map<String,dynamic>));
        }
    }
  }

解决方法

核心问题

从Firestore读取的participants字段默认是List<dynamic>类型,但模型中定义的是List<String>,类型不匹配导致转换失败。

修改模型的fromMap方法

显式将List<dynamic>转换为List<String>,同时对chatroomid添加类型断言避免潜在问题:

factory ChatRoomModel.fromMap(Map<String, dynamic> map) {
  return ChatRoomModel(
    chatroomid: map['chatroomid'] as String,
    participants: (map['participants'] as List<dynamic>).cast<String>(),
  );
}

优化fetchData方法

原方法中qsnapshot.docs.map((e) => e).toList()属于冗余操作,直接使用qsnapshot.docs即可:

Future<void> fetchData() async {
  QuerySnapshot qsnapshot = await FirebaseFirestore.instance.collection("chatrooms").get();
  final int num_of_rooms = qsnapshot.docs.length;
  print(num_of_rooms);
  if (num_of_rooms > 0) {
    List<ChatRoomModel> templist = [];
    for (var doc in qsnapshot.docs) {
      templist.add(ChatRoomModel.fromMap(doc.data() as Map<String, dynamic>));
    }
    // 此处可添加templist的后续处理逻辑,比如更新状态
  }
}

内容的提问来源于stack exchange,提问作者Irfan Ganatra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 19:13:34