简体   繁体   中英

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?

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();
      ...

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM