I am trying to retrieve nested array data from Firebase and display it on ListView Builder but I got an error of this below.
Exception has occurred.
StateError (Bad state: field does not exist within the DocumentSnapshotPlatform)
Please guide me. I need help.
The model that I used to store the nested data to main collection
class SPMModel {
String? subjectName;
String? subjectGrade;
SPMModel(this.subjectName, this.subjectGrade);
Map<String, dynamic> toMap() => {
"subjectName": subjectName,
"subjectGrade": subjectGrade,
};
}
The model of the main collection
class UserProfileModel {
String? uid;
String? email;
String? fullName;
String? nric;
String? age;
String? gender;
String? ethnicity;
String? religion;
String? address;
String? state;
String? country;
String? phone;
String? parentName;
String? parentPhone;
List<dynamic>? spmResult = []; //I'm using this variable to store the SPMModel data
UserProfileModel({
this.uid,
this.email,
this.fullName,
this.nric,
this.age,
this.gender,
this.ethnicity,
this.religion,
this.address,
this.state,
this.country,
this.phone,
this.parentName,
this.parentPhone,
this.spmResult
});
//receive data from database
factory UserProfileModel.fromMap(map) {
return UserProfileModel(
uid: map['uid'],
email: map['email'],
fullName: map['fullName'],
nric: map['nric'],
age: map['age'],
gender: map['gender'],
ethnicity: map['ethnicity'],
religion: map['religion'],
address: map['address'],
state: map['state'],
country: map['country'],
phone: map['phone'],
parentName: map['parentName'],
parentPhone: map['parentPhone'],
spmResult: map['spmResult']
);
}
//send data to database
Map<String, dynamic> toMap() {
return {
'uid': uid,
'email': email,
'fullName': fullName,
'nric': nric,
'age': age,
'gender': gender,
'ethnicity': ethnicity,
'religion': religion,
'address': address,
'state': state,
'country': country,
'phone': phone,
'parentName': parentName,
'parentPhone': parentPhone,
'spmResult': spmResult
};
}
}
My StreamBuilder
StreamBuilder<QuerySnapshot>(
stream: FirebaseFirestore.instance.collection("users").where('uid', isEqualTo: FirebaseAuth.instance.currentUser!.uid).snapshots(),
builder: (context, snapshot){
if(!snapshot.hasData){
return const Center(child: Text('No data found'),);
}
return ListView.builder(
shrinkWrap: true,
itemCount: snapshot.data!.docs.length,
itemBuilder: (context, index){
return Column(
children: <Widget>[
Text('id : ${snapshot.data!.docs[index].toString()}'),
Text('subject: ${snapshot.data!.docs[index]['subjectName']}'),
Text('grade: ${snapshot.data!.docs[index]['subjectGrade']}'),
],
);
}
);
}
)

