user1012500
user1012500

Reputation: 1637

FlutterFire DocumentSnapshot.data() is returning Object?

I'm in the process of upgrading my libraries in my flutter app as well as move to null-safety. I'm using cloud_firestore version 2.2.1.

In my model i have a factory method that takes a documentsnapshot, I'm receiving the error

A value of type 'Object?' can't be assigned to a variable of type 'Map<String, dynamic>'.

factory Account.fromDoc(DocumentSnapshot doc) {

    if(doc.exists)
    {
      Map<String, dynamic> data = doc.data();
      ...

    }

Documentation at https://firebase.flutter.dev/docs/firestore/usage/ states that

If the document exists, you can read the data of it by calling the data method, which returns a Map<String, dynamic>, or null if it does not exist

So I'm not sure why it is returning it as a type of Object? when I'm expecting Map<String, dynamic> or what I need to do. How can I get this to work ?

Upvotes: 1

Views: 1323

Answers (1)

Yazeed AlKhalaf
Yazeed AlKhalaf

Reputation: 323

Basically you have to add a type to the DocumentSnapshot, this occured to me and this is how I solved it:

factory Account.fromDoc(DocumentSnapshot<Map<String, dynamic>> doc) { // here the type should be specified

    if(doc.exists)
    {
      Map<String, dynamic> data = doc.data();
      ...

    }
}

Upvotes: 3

Related Questions