如何使Firebase集合的每个文档为ListTile?



我有一个代码来显示与点导航的页面视图中的图像列表。但是对于我的项目,我需要显示同一文档的几个字段,这是我的Firebase集合的每个文档的字段。似乎我需要把我所有的文档作为一个列表,不知道如何做到这一点,也不知道如何得到我的文档的每个字段,然后…有人知道吗?

这是我用来显示图像列表的代码:

class SwipeImages extends StatefulWidget {
final List imageList;
const SwipeImages({
Key? key,
required this.imageList,
}) : super(key: key);
@override
_SwipeImagesState createState() => _SwipeImagesState();
}
class _SwipeImagesState extends State<SwipeImages> {

int _selectedPage = 0;
@override
Widget build(BuildContext context) {
return Container(
height: 500,
width: 500,
child: ClipRRect(
borderRadius: BorderRadius.circular(20),
child: Stack(
children: [
PageView(
onPageChanged: (num) {
setState(() {
_selectedPage = num;
});
},
children: [
for(var i=0; i < widget.imageList.length; i++)
Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
),
child: Image.network(
"${widget.imageList[i]}",
fit: BoxFit.cover,
), 
),
),
]
),
Positioned(
bottom: 20,
right: 0,
left: 0,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
for(var i=0; i < widget.imageList.length; i++)
AnimatedContainer(
duration: Duration(
milliseconds: 300
),
curve: Curves.easeInOutCubic,
width: _selectedPage == i ? 30.0 : 10.0,
height: 10.0,
margin: EdgeInsets.symmetric(
horizontal: 5,
),
decoration: BoxDecoration(
color: Black.withOpacity(0.4),
border: Border.all(
width: 0.25,
color: Black.withOpacity(0.6)
),
borderRadius: BorderRadius.circular(10)
),
),
],
),
),
]
),
),
);
}
}

class DisplayImages extends StatelessWidget {
@override
Widget build(BuildContext context) {
CollectionReference images = firestore.collection('Images');
return FutureBuilder(
future: product.doc('My Document').get(),
builder: (context, AsyncSnapshot<DocumentSnapshot> snapshot) {
if(snapshot.connectionState == ConnectionState.done) {
DocumentSnapshot<Object?> data = snapshot.data!;
List images = data['Images'];
// The field is an array with urls of the images I want to display;
return SwipeImages(imageList: images);
}
}
);
}
}

保持简单,为什么不传递从FutureBuilder()获得的整个文档呢?这样,您就可以访问所有字段(考虑到您有模型类,如果没有,那么您将不得不使用.data访问字段),而不必再次进行网络调用。

像这样,

DocumentSnapshot<Object?> data = snapshot.data!;

return SwipeImages(doc: data);//now you can use the whole separate doc and access all the fields.

如果您需要一个恒定的文档流(多个文档),那么您将不得不使用流。更多信息请访问https://dart.dev/tutorials/language/streams

使用Streambuilder -

StreamBuilder(
stream: stream,
builder: (BuildContext context,
AsyncSnapshot<List<DocumentSnapshot>> snapshots) {
if (snapshots.connectionState == ConnectionState.active &&
snapshots.hasData) {
print(snapshots.data);
return ListView.builder(
itemCount: snapshots.data.length,
itemBuilder: (BuildContext context, int index) {
DocumentSnapshot doc = snapshots.data[index];

return Text(
" Do anything with the stream of data",
);
},
);
} else {
return Center(child: CircularProgressIndicator());
}
},
),

试着这样修改你的代码:

List images = data.get('Images');

最新更新