我在尝试从firebase获取数据并更新值时遇到了麻烦。
我有一个餐馆名称和它被选中的次数(用户选择去那个餐馆吃饭)。我试图检索numPicked,如果用户决定再次去那里,我就通过添加一个来更新它。
在这里,我试图获取一个特定的文档,并试图存储docID和变量,我需要更新。
Future<bool> searchQuery(
{required String restaurantName,
required var userID,
required db}) async {
int addOne = 1; //addes one if it has been picked
//this is not working
try {
Query query2 =
db.where('userId', isEqualTo: FirebaseAuth.instance.currentUser!.uid);
Query query = query2.where('restaurantName', isEqualTo: restaurantName);
await query.get().then((querySnapshot) {
// ignore: avoid_function_literals_in_foreach_calls
querySnapshot.docs.forEach((doc) {
docID = doc.id;
numPicked = doc['numPicked'];
restaurantExist = true;
});
}).catchError((error) {
// print('error querying: #error');
});
} catch (ex) {
// ignore: avoid_print
print(ex);
}
//this is not working
int totalPicked = numPicked + addOne;
//if the restaurant exist then update the numpicked for that specific restaurant
if (restaurantExist) {
try {
var query = db
//.collection('NumRestaurantPicked')
.doc(docID);
await query.update({'numPicked': totalPicked.toString()});
} catch (ex) {}
}
return restaurantExist;
}
1条答案
按热度按时间9fkzdhlc1#
docID和numPicked变量没有在方法签名中定义,因此在try块之外无法访问它们。它们应该定义为类变量,以便可以从其他方法访问它们。