Can someone explain fromMap() and fromSnapshot() to me

Issue

Can someone explain the below code to me?I was learning cloud firestore in flutter and i am not able to understand below fromMap conecpt and fromSnapshot conept

class Record {
     final String name;
     final int votes;
     final DocumentReference reference;
    
     Record.fromMap(Map<String, dynamic> map, {this.reference})
         : assert(map['name'] != null),
           assert(map['votes'] != null),
           name = map['name'],
           votes = map['votes'];
    
     Record.fromSnapshot(DocumentSnapshot snapshot)
         : this.fromMap(snapshot.data, reference: snapshot.reference);
    
     @override
     String toString() => "Record<$name:$votes>";
    }

Solution

fromMap() The data which received from API is in JSON format, so it’s a key-value pair relationship and for that map is used. And it’s used basically to parse the value from the map and assign it to local variables in the model

Example:

 name = map['name'], 
 votes = map['votes'];

Above both variables are accessible from model object instance.

fromSnapshot(): It’s similar to fromMap(), the only difference is that it’s giving its values in DocumentSnapshot, and call fromMap()

Answered By – Jitesh Mohite

Answer Checked By – David Goodson (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *