首页 > 解决方案 > 读取 Firestore 集合时出现错误“无法将参数类型‘对象’分配给参数类型‘字符串’”

问题描述

我试图从 firebaseFirestore 获取数据,但它在下面显示错误,这篇文章也没有帮助https://firebase.flutter.dev/docs/firestore/usage/#typing-collectionreference-and-documentreference

代码

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:greatr/models/ChatRoom.dart';

FirebaseFirestore firestore = FirebaseFirestore.instance;

    Future getChatRooms() async {
      List<ChatRoom> rooms = [];
      QuerySnapshot response = await firestore.collection('chat_rooms').get();
      response.docs.forEach((element) {
        rooms.add(ChatRoom.fromJson(element.data()!));
      });
     
    }

错误

The argument type 'Object' can't be assigned to the parameter type 'String'.

标签: firebasefluttergoogle-cloud-firestore

解决方案


您不共享ChatRoom该类的代码,但我假设它与您在问题中引用Movie的文档中的类的示例相似。

如果这个假设是正确的,那么以下应该可以解决问题:

final chatRoomsRef = FirebaseFirestore.instance.collection('chat_rooms').withConverter<ChatRoom>(
      fromFirestore: (snapshot, _) => ChatRoom.fromJson(snapshot.data()!),
      toFirestore: (chat_room, _) => chat_room.toJson(),
    );

//...


Future getChatRooms() async {

  List<QueryDocumentSnapshot<ChatRoom>> chat_rooms = await chatRoomsRef
      .get()
      .then((snapshot) => snapshot.docs);     
   //...

}

推荐阅读