[英]Im trying to write code to get (doc id) from Firebase
看看我的数据库结构:
这是我想在其中使用 ID 的代码:
Widget build(BuildContext context) {
return SafeArea(
child: InkWell(
borderRadius: BorderRadius.circular(30),
child: Dismissible(
key: UniqueKey(),
direction: DismissDirection.startToEnd,
background: Container(
color: Colors.red,
child: Row(
children: [
Icon(Icons.delete),
Text(
'Move to trash',
style: TextStyle(
color: Colors.white,
fontFamily: 'Righteous',
),
)
],
),
),
confirmDismiss: (DismissDirection direction) async {
return await showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text("Delete Confirmation"),
content: Text("Are you sure you want to delete this item?"),
actions: <Widget>[
TextButton(
onPressed: () => Navigator.of(context).pop(true),
child: const Text("Delete")),
TextButton(
onPressed: () => Navigator.of(context).pop(false),
child: const Text("Cancel"),
),
],
);
});
},
onDismissed: (DismissDirection direction) async {
if (direction == DismissDirection.startToEnd) {
print('item deleted');
}
await deleteCar(
'wam4jSgeIpWHIBLVXvmv'); //I want to get doc ID to delete it
},
有一些方法:
FirebaseFirestore.instance
.collection('$YOUR_COLLECTION')
.where('uid', isEqualTo: "$UID_OF_THAT_ITEM").limit(1).get().then((value) => value.docs.first.id);
当你得到它 value.docs.first.id 是你所需要的。
不确定我是否理解您想要实现的目标。 但是在我看来,例如,当您创建它时,您可以将该 id 复制为元素的属性。
"aasdasd" :{
"id": "aasdasd",
"carName": "car",
}
或者当您使用 map 汽车时,使用您获得的密钥作为汽车 Model 的属性。 这是产品的一个例子。
static Future loadProducts() async {
final url = Uri.https(_baseUrl, 'products.json');
final res = await http.get(url);
final Map<String, dynamic> productsMap = json.decode(res.body);
final List<Product> products = productsMap.keys
.map((key) => Product(
id: key,
name: productsMap[key]['name'],
description: productsMap[key]['description'],
price: productsMap[key]['price'],
imagen: productsMap[key]['imagen'],
isAvailable: productsMap[key]['isAvailable'],
))
.toList();
return products;
}
'key' 是你想要的值。
这一行解决了问题:
String gg = await FirebaseFirestore.instance
.collection('carsData')
.where('uid', isEqualTo: loggedInUser.uid)
.where('CarName', isEqualTo: nameCar)
.limit(1)
.get()
.then((value) => value.docs.first.id);
但是当您有 2 个项目具有相同的 CarName 时,您必须添加另一个 where() 以获取特定的 ID。
FirebaseFirestore.instance
.collection('carsData')
.where('uid', isEqualTo: 'selected_car_uid')
.get()
.then((value) {
value.docs.forEach((element) {
print(element.id); // you will get your firestore id and then delete via this id.
FirebaseFirestore.instance
.collection("carsData")
.doc(element.id)
.delete()
.then((value_2) {
print('========> successfully deleted');
});
});
});
快乐编码:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.