Hello guys I am using a stream builder to get data from fireStore collection to display some posts but I am getting an error saying type 'Null' is not a subtype of type 'String' and the value of the snapshot is null
this is the post model that I have
class Post {
final String id;
final String description;
final String validUntil;
final String availableFor;
final String imageUrl;
final String owner;
Post({
required this.id,
required this.description,
required this.validUntil,
required this.availableFor,
required this.imageUrl,
required this.owner,
});
Map<String, dynamic> toJson() => {
'id': id,
'description': description,
'validUntil': validUntil,
'availableFor': availableFor,
'imageUrl': imageUrl,
'owner': owner,
};
static Post fromJson(Map<String, dynamic> json) => Post(
id: json['id'],
description: json['description'],
validUntil: json['validUntil'],
availableFor: json['availableFor'],
imageUrl: json['imageUrl'],
owner: json['owner'],
);
}
and this is the Stream
Stream<List<Post>> readPosts() => FirebaseFirestore.instance
.collection('posts')
.snapshots()
.map((snapshot) =>
snapshot.docs.map((doc) => Post.fromJson(doc.data())).toList());
and this is the StreamBuilder
StreamBuilder<List<Post>>(
stream: readPosts(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.active) {
if (snapshot.data == null) {
print(snapshot.error.toString());
return Text(snapshot.error.toString());
} else {
final posts = snapshot.data;
return Column(
children: posts!.map(buildPost).toList(),
);
}
} else {
return Center(
child: CircularProgressIndicator(),
);
}
})
I would really appreciate it if you can help me solve this problem
CodePudding user response:
Likely one of the values in the Post is null in Firebase, such as description or imageUrl. Print the doc to try troubleshooting the problem like this:
Stream<List<Post>> readPosts() =>
FirebaseFirestore.instance.collection('posts').snapshots().map((snapshot) {
print(snapshot);
return snapshot.docs.map((doc) {
print(doc.data());
return Post.fromJson(doc.data());
}).toList();
});
CodePudding user response:
As i seen in your code you have created model which not-null
type model
create nullable
model for that you can use