Reputation: 2837
I'm getting the following error when trying to work with Firestore and Stream Provider
type '_JsonQueryDocumentSnapshot' is not a subtype of type 'Map<String, dynamic>' in type cast
Here is my root page
ChangeNotifierProxyProvider<AuthProvider, DogProvider>(
update: (context, value, previous) => DogProvider(), // ..getDogList()
create: (_) => DogProvider(), //..getDogList()
),
StreamProvider<Object>(
create: (context) =>
DogFirestoreService().getDogs('GeVnAbdq9BWs1STbytlAU65qkbc2'),
initialData: 10,
child: const DogsListScreen(),
),
My Firestore Service getting the stream
Stream<List<DogModel>> getDogs(String uid) {
return dogCollection.where('userId', isEqualTo: uid).snapshots().map(
(snapshot) => snapshot.docs
.map((document) => DogModel.fromFire(document))
.toList(),
);
}
The model
@JsonSerializable(explicitToJson: true)
class DogModel {
String? dogImage;
String dogName;
DogBreed? breedInfo;
@JsonKey(fromJson: dateTimeFromTimestamp, toJson: dateTimeAsIs)
DateTime? dogBirthday;
double? dogWeight;
DogWeight? weightType;
DogGender? dogGender;
List<String>? dogType;
DogStatus? dogStatus;
bool? registered;
String? dogChipId;
@JsonKey(fromJson: dateTimeFromTimestamp, toJson: dateTimeAsIs)
DateTime? createdAt;
DogStats? dogStats;
@JsonKey(ignore: true)
String? id;
String? userId;
DogModel({
required this.dogImage,
required this.dogName,
required this.breedInfo,
required this.dogBirthday,
required this.dogWeight,
required this.weightType,
required this.dogGender,
required this.dogType,
required this.dogStatus,
required this.registered,
this.dogStats,
this.dogChipId,
this.createdAt,
this.userId,
this.id,
});
factory DogModel.fromFire(QueryDocumentSnapshot snapshot) {
return DogModel.fromJson(snapshot as Map<String, dynamic>);
}
// JsonSerializable constructor
factory DogModel.fromJson(Map<String, dynamic> json) =>
_$DogModelFromJson(json);
// Serialization
Map<String, dynamic> toJson() => _$DogModelToJson(this);
}
And in the widget
Widget build(BuildContext context) {
final test = context.watch<Object>();
print(test);
Upvotes: 1
Views: 717
Reputation: 2984
As we discussed in the other question, you need to extract the data from the document as follow:
Stream<List<DogModel>> getDogs(String uid) {
return dogCollection.where('userId', isEqualTo: uid).snapshots().map(
(snapshot) => snapshot.docs
.map((document) => DogModel.fromJson(document.data()) // <~~ here
.toList(),
);
As you see, you should call document.data()
(not document.data
, which was my mistake earlier).
Upvotes: 2