'error when trying to get data from "data"
I'm getting this error when trying to get data from my "data".
child: StreamBuilder<QuerySnapshot>(
stream:
FirebaseFirestore.instance.collection('messages').snapshots(),
builder: (context, snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
case ConnectionState.waiting:
// ignore: prefer_const_constructors
return Center(
// ignore: prefer_const_constructors
child: CircularProgressIndicator(),
);
default:
List<DocumentSnapshot> documents =
snapshot.data!.docs.reversed.toList();
return ListView.builder(
itemCount: documents.length,
reverse: true,
itemBuilder: (context, index) {
return ChatMessage(documents[index].data); erro here
});
}
},
),
estou usando ChatMessage(this.data); final Map<String, dynamic> data;
Solution 1:[1]
The class definition of DocumentSnapshot
looks like DocumentSnapshot<T extends Object?>
, with T
being the generic parameter. The error in your code says:
The argument type 'Object?' can't be assigned to the parameter type 'Map<String, dynamic>'
This hints to the fact that your ChatMessage
class constructor expects an input of type Map<String, dynamic>
but data()
of DocumentSnapshot
returns T?
(https://pub.dev/documentation/cloud_firestore/latest/cloud_firestore/DocumentSnapshot/data.html). Since you did not provide DocumentSnapshot
with a concrete type it assumes it to be Object?
.
One solution here is to provide DocumentSnapshot
with the concrete type you expect it to store/return. In your case that would be here:
List<DocumentSnapshot<Map<String, dynamic>> documents =
snapshot.data!.docs.reversed.toList();
Furthermore you need to cast away the nullability of T?
, otherwise you would get another error (notice the postfix exclamation mark):
return ChatMessage(documents[index].data()!);
Solution 2:[2]
I realized that what you wrote is not exactly the same as what is in the photo, for text it is just .date
and for the photo it is .data()
Assuming that it is .data
always the parentheses, it is possible to use the cast if you are sure that the type that is in date is the same type that will go into ChatMessage
if it is you can do that
return ChatMessage(documents[index].data.cast<Map<String, dynamic>>());
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | puelo |
Solution 2 | Miguel Vieira Colombo |