I want read data from my firestore collection specific document and then the format below as a Map
NEED HELP IN data serialization
Cast Error but Need Data Modeling
**Need Help ** while using stream builder i faced some errors and i can't make them simplified as I need help to understand factory function **because in flutter and dart new upcoming will prefer factory function **
#String? callerId;
String? callerName;
String? callerPic;
String? receiverId;
String? receiverName;
String? receiverPic;
String? channelId;
bool? hasDialled;
Call({
this.callerId,
this.callerName,
this.callerPic,
this.receiverId,
this.receiverName,
this.receiverPic,
this.channelId,
this.hasDialled,
});
Map<String, dynamic> toMap(Call call) {
Map<String, dynamic> callMap = Map();
callMap["caller_id"] = call.callerId;
callMap["caller_name"] = call.callerName;
callMap["caller_pic"] = call.callerPic;
callMap["receiver_id"] = call.receiverId;
callMap["receiver_name"] = call.receiverName;
callMap["receiver_pic"] = call.receiverPic;
callMap["channel_id"] = call.channelId;
callMap["has_dialled"] = call.hasDialled;
return callMap;
}
Call.fromMap(Map callMap) {
this.callerId = callMap["caller_id"];
this.callerName = callMap["caller_name"];
this.callerPic = callMap["caller_pic"];
this.receiverId = callMap["receiver_id"];
this.receiverName = callMap["receiver_name"];
this.receiverPic = callMap["receiver_pic"];
this.channelId = callMap["channel_id"];
this.hasDialled = callMap["has_dialled"];
}
}
CollectionReference callcollection =
FirebaseFirestore.instance.collection(CALL_COLLECTION);
Stream<DocumentSnapshot> callStream({String? uid}) =>
callcollection.doc(uid).snapshots();
StreamBuilder<DocumentSnapshot>(
stream: callMethods.callStream(
uid: FirebaseAuth.instance.currentUser!.uid),
builder: (context, snapshot) {
if (snapshot.hasData && snapshot.data?.data != null) {
Map<String , dynamic> data = snapshot.data?.data() as Map<String , dynamic>;
**HERE IS The PROBLEM _CastError (type '_JsonDocumentSnapshot' is not a subtype of type 'Map<String, dynamic>' in type cast)
but i need data as a map **
Call call = Call.fromMap(data);
if (!call.hasDialled!) {
return PickupScreen(call: call);
}
}
CodePudding user response:
Can you try this:
Map<String , dynamic>? data = snapshot.data?.data() // maybe use null check operator instead of question mark.
or try this:
var data = snapshot.data?.data()
CodePudding user response:
It was just simple Call data = Call( **all key values** ) var data = snapshot.data 'key' :data['place key'] use type be like this for all key values Call call = Call.fromMap(data); not required any more
