Reputation: 181
I stored a list of Map data in firestore database. But when I tried to fetch the data to a variable of type List<Map<String, dynamic>>, it shows the error "_CastError (type 'List' is not a subtype of type 'List<Map<String, dynamic>>' in type cast)".
Here is the code,
// code to fetch objects list from database
Future<List<Map<String, dynamic>>> getUserObjects() async {
Map<String, dynamic> userInfo = await getUserInfo();
List<Map<String, dynamic>> userObjects = userInfo['objects'] as List<Map<String, dynamic>>;
List<Map<String, dynamic>> result = [];
for(var i=0; i<userObjects.length; i++) {
var docInfo = await DatabaseMethods().getDocumentInfo(findCollectionName(userObjects[i]['objectType']), userObjects[i]['docId']) as Map<String, dynamic>;
result.add({'icon': findIcon(userObjects[i]['objectType']), 'objectName' : docInfo['objectName'], 'docId' : userObjects[i]['docId']});
}
return result;
}
Future<Map<String, dynamic>> getUserInfo() async {
var user = await FirebaseAuthentication().getCurrentUser();
Map<String, dynamic> userInfo = await DatabaseMethods().getuserFromDB(user.uid);
if(userInfo['objects'] == null) {
userInfo.addAll({'objects' : []});
}
return userInfo;
}
final FirebaseAuth auth = FirebaseAuth.instance;
Future<User> getCurrentUser() async {
return auth.currentUser!;
}
// code to add an object to object list in collection 'user'
Future<void> updateUserObjectList(Map<String, dynamic> object) async {
var user = await FirebaseAuthentication().getCurrentUser();
var userId = user.uid;
await FirebaseFirestore.instance.collection('users').doc(userId)
.update({'objects' : FieldValue.arrayUnion([object])});
}
The data stored in the database will look like the below image with the following changes,
Can someone say where the error happened. Code gives the error in the line "List<Map<String, dynamic>> userObjects = userInfo['objects'] as List<Map<String, dynamic>>;" in getUserObjects method
Upvotes: 0
Views: 202
Reputation: 2904
Moving the OP's solution into an answer for this question, this specific issue was caused by sending an incorrect document.id
in the fetch call.
Using the correct document ID (user.id + datetime
for the OP's case) solved the problem.
Upvotes: 1