在这里,我已编写了用于访问集合中所有文档的代码,并将其显示在ListView中。
这是获取数据的方法。
Future getData() async {
var firestore = Firestore.instance;
QuerySnapshot qn =
await firestore.collection("LiveProducts").getDocuments();
return qn.documents;
}
这是我的构建方法。
@override
Widget build(BuildContext context) {
return Container(
child: FutureBuilder(
future: getData(),
builder: (_, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Padding(
padding: const EdgeInsets.only(
top: 295,
),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Center(
child: SpinKitCircle(
color: Colors.deepPurpleAccent,
size: 50.0,
),
),
],
),
);
} else {
return ListView.builder(
// title: Text(snapshot.data[index].data["ProductName"]),
shrinkWrap: true,
itemCount: snapshot.data.length,
itemBuilder: (_, index) {
return InkWell(
onTap: onClick,
child: Container(
child: Container(
margin: EdgeInsets.all(15),
height: 300,
width: double.infinity,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
image: DecorationImage(
image: NetworkImage(snapshot
.data[index].data["ProductImageLink"]),
fit: BoxFit.cover,
),
boxShadow: [
BoxShadow(
color: Colors.deepPurpleAccent,
blurRadius: 8,
offset: Offset(0, 10),
)
],
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Row(
children: <Widget>[
Expanded(
child: Padding(
padding: const EdgeInsets.all(15.0),
child: Column(
crossAxisAlignment:
CrossAxisAlignment.start,
children: <Widget>[
Text(
// name,
snapshot.data[index]
.data["ProductName"],
style: TextStyle(
color: Colors.white,
fontSize: 30,
fontWeight: FontWeight.bold),
),
SizedBox(
height: 10,
),
Text(
// type,
// '',
snapshot.data[index]
.data["ProductCompany"],
style: TextStyle(
color: Colors.white,
fontSize: 20,
fontWeight: FontWeight.bold),
),
],
),
),
),
],
),
void onClick() {
Navigator.of(context).push(MaterialPageRoute(builder: (_) {
return PlacingBids();
}));
}
我已经在ListView中列出了所有文档,但是我遇到了问题。我需要在ListView上获取单击文档的Firestore ID。我该怎么办?
答案 0 :(得分:0)
DocumentSnapshot
类具有id
属性,该属性返回文档密钥。
您可以使用GestureDedector
包装列表项,并将文档ID传递给“ nTap”回调。
@override
Widget build(BuildContext context) {
return Container(
child: FutureBuilder(
future: getData(),
builder: (_, AsyncSnapshot<List<DocumentSnapshot>> snapshot) {
if (snapshot.hasData) {
return ListView.builder(
itemBuilder: (_, index) {
return GestureDetector(
onTap: () {
print("Item with key " +
snapshot.data[index].id +
" clicked.");
},
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text(snapshot.data[index].data["ProductName"]),
),
);
},
itemCount: snapshot.data.length,
);
}
return Container();
},
),
);
}