如何从firebase检索数据以显示产品



我试图在主页上展示我的产品,从firestore集合中提取,并使用StreamBuilder显示它。但是我的主屏幕显示的是它返回"hihihihi"。我使用了正确的集合引用和正确的字段名。

在这种情况下,您的帮助将帮助初学者扑动开发人员完成他的大学项目。

感谢我的代码

Container(
height: 190,
child: StreamBuilder(
stream: collectionReference.snapshots(),
builder: (BuildContext context,
AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasData) {
return ListView.builder(
scrollDirection: Axis.horizontal,
padding: EdgeInsets.only(left: 16, right: 6),
itemCount: 4,
itemBuilder: (context, index) {
children:
snapshot.data!.docs.map(
(e) => Container(
margin: EdgeInsets.only(right: 10),
height: 199,
width: 344,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(28),
color: Colors.white,
boxShadow: [
BoxShadow(
color: Colors.grey,
offset: Offset(0.0, 1.0), //(x,y)
blurRadius: 6.0,
),
],
),
child: Stack(
children: [
Padding(
padding: const EdgeInsets.all(10.0),
child: Positioned(
child: Image(
image: AssetImage(
'assets/item1.png',
),
height: 200,
),
),
),
Positioned(
right: 20,
top: 10,
child: Text(
e['name'],
style: TextStyle(
color: Colors.black,
fontSize: 25,
fontFamily: 'Poppins',
fontWeight: FontWeight.bold),
),
),

Positioned(
right: 20,
bottom: 10,
child: Text(
e['price'],
style: TextStyle(
color: Colors.black,
fontSize: 30,
fontFamily: 'Poppins'),
),
),
],
),
),
);
return Center(child: Text('hi'));
});
}
return Center(child: Text('Empty'));
}),
),

问题是itemBuilder应该返回ListView中的每个项目将如何构建。目前您所做的是映射整个快照,然后返回一个包含hi的plan Text小部件。试试下面的itemBuilder代码:

itemBuilder: (context, index) {
final e = snapshot.data!.docs[index];
return Container(
margin: EdgeInsets.only(right: 10),
height: 199,
width: 344,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(28),
color: Colors.white,
boxShadow: [
BoxShadow(
color: Colors.grey,
offset: Offset(0.0, 1.0), //(x,y)
blurRadius: 6.0,
),
],
),
child: Stack(
children: [
Padding(
padding: const EdgeInsets.all(10.0),
child: Positioned(
child: Image(
image: AssetImage(
'assets/item1.png',
),
height: 200,
),
),
),
Positioned(
right: 20,
top: 10,
child: Text(
e['name'],
style: TextStyle(
color: Colors.black,
fontSize: 25,
fontFamily: 'Poppins',
fontWeight: FontWeight.bold),
),
),

Positioned(
right: 20,
bottom: 10,
child: Text(
e['price'],
style: TextStyle(
color: Colors.black,
fontSize: 30,
fontFamily: 'Poppins'),
),
),
],
),
);
}

还要记住,你的itemCount是4,你可能希望它是:

itemCount: snapshot.data!.docs.length