skip to Main Content

I’m following the documentation here to use custom objects when reading and writing cloud firestore.

Client class:

class Client {
  String id;
  String name;
  String email;
  int contactNumber;

  Client({
    required this.id,
    required this.name,
    required this.email,
    required this.contactNumber,
  });

  factory Client.fromFirestore(
    DocumentSnapshot<Map<String, dynamic>> snapshot,
    SnapshotOptions? options,
  ) {
    final data = snapshot.data();
    return Client(
      id: data?['id'],
      name: data?['name'],
      email: data?['email'],
      contactNumber: data?['contactNumber'],
    );
  }

  Map<String, dynamic> toFirestore() {
    return {
      "id": id,
      "name": name,
      "email": email,
      "contactNumber": contactNumber
    };
  }
}

Creating collection ref along with withConverter:

  CollectionReference usersCollection = FirebaseFirestore.instance
      .collection('users')
      .withConverter(
          fromFirestore: Client.fromFirestore,
          toFirestore: (Client client, options) => client.toFirestore());

But I get the following error:

The argument type ‘Map<String, dynamic> Function(Client, SetOptions?)’ can’t be assigned to the parameter type ‘Map<String, Object?> Function(Object?, SetOptions?)’.

Not sure what I’m missing here.

2

Answers


  1. Chosen as BEST ANSWER

    Okay turns out you don't do it for a collection but only when you're actually getting documents.

    This works:

      static Future<List<Client>> getAllClients() async {
        QuerySnapshot snapshot = await clientCollection
            .withConverter(
                fromFirestore: Client.fromFirestore,
                toFirestore: (Client client, options) => client.toFirestore())
            .get();
    
        return snapshot.docs.map((doc) => doc.data() as Client).toList();
      }
    

    Also this for getting it as a Stream:

      static Stream<List<Client>> getAllClientsStream() {
        return clientCollection
            .withConverter(
                fromFirestore: Client.fromFirestore,
                toFirestore: (Client client, options) => client.toFirestore())
            .snapshots()
            .map(
              (querySnapshot) =>
                  querySnapshot.docs.map((doc) => doc.data()).toList(),
            );
      }
    

  2. Try to update the DataType:

    CollectionReference usersCollection = FirebaseFirestore.instance
      .collection('users')
      .withConverter(
         fromFirestore: Client.fromFirestore,
         toFirestore: (Client client, SetOptions? options) => client.toFirestore());  // update this line
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search