gpt4 book ai didi

firebase - 如何使用 QuerySnapshot 在 firestore flutter 中获取文档 ID

转载 作者:行者123 更新时间:2023-12-05 04:45:26 24 4
gpt4 key购买 nike

This is the image of my firesoter database

我正在尝试使用 QuerySnapshot 从我的数据库中获取数据(实时)。我也需要更新我的数据。这是我的方法,我不知道如何在这个方法中获取我的 documentID。

class LoadData extends StatefulWidget {
const LoadData({Key? key}) : super(key: key);

@override
_LoadDataState createState() => _LoadDataState();
}

class _LoadDataState extends State<LoadData> {
//Read Data in realTime Snapshot
final Stream<QuerySnapshot> _cupCakeStream = FirebaseFirestore.instance
.collection('cupcake')
.snapshots(includeMetadataChanges: true);

@override
Widget build(BuildContext context) {
return StreamBuilder<QuerySnapshot>(
stream: _cupCakeStream,
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasError) {
return Text('Something went wrong');
}

if (snapshot.connectionState == ConnectionState.waiting) {
return Text("Loading");
}

return ListView(
shrinkWrap: true,
children: snapshot.data!.docs.map((DocumentSnapshot document) {
Map<String, dynamic> data =
document.data()! as Map<String, dynamic>;
print(data); //**Print collection only..I need to get documentID with each collection**
return ListTile(
title: Text(data['cupcake_name']),
subtitle: Text(data['description']),
);
}).toList(),
);
},
);
}
}

最佳答案

文档 是一个 DocumentSnapshot并且有一个 id属性(property)。

因此,以下应该可以解决问题:

    return ListView(
shrinkWrap: true,
children: snapshot.data!.docs.map((DocumentSnapshot document) {
Map<String, dynamic> data =
document.data()! as Map<String, dynamic>;
print(data);

print(document.id); // <= Should print the doc id

return ListTile(
title: Text(data['cupcake_name']),
subtitle: Text(data['description']),
);
}).toList(),
);

关于firebase - 如何使用 QuerySnapshot 在 firestore flutter 中获取文档 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69129238/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com