我收到一个云Firestore异常,该异常表示“执行事务时出错,在事务中读取的每个文档也必须写入。为空”。仅当我尝试通过用户的电子邮件创建用户文档来运行事务时,才会出现此问题,当它位于UID上时,一切正常。
Future<bool> updateFavorites(String email,String recipeId) {
DocumentReference favoritesReference =
Firestore.instance.collection('users').document(email);
return Firestore.instance.runTransaction((Transaction tx) async {
Documentsnapshot postsnapshot = await tx.get(favoritesReference);
if (postsnapshot.exists) {
if (!postsnapshot.data['favorites'].contains(recipeId)) {
await tx.update(favoritesReference,<String,dynamic>{
'favorites': FieldValue.arrayUnion([recipeId])
});
} else {
await tx.update(favoritesReference,dynamic>{
'favorites': FieldValue.arrayRemove([recipeId])
});
}
} else {
await tx.set(favoritesReference,{
'favorites': [recipeId]
});
}
}).then((result) {
return true;
}).catchError((error) {
print('Error: $error');
return false;
});
}
这是进行交易的函数,此函数在这里称为:
void handleFavoritesListChanged(String recipeID) {
updateFavorites(appState.user.email,recipeID) //the user hold the current firebase user
.then((result) {
if (result == true) {
setState(() {
if (!StateModel.favorites.contains(recipeID))
StateModel.favorites.add(recipeID);
else
StateModel.favorites.remove(recipeID); //StateModel is a class which has the empty list of favorites
});
}
});
}
当我使用user.uid而不是use.email时,上述代码非常有用。 请帮助