![](/img/trans.png)
[英]Getting all documents uids from firestore and add them to a list .flutter
[英]How to list values from documents in Flutter Firestore?
如果您不使用任何 state 管理解决方案(Riverpod、Provider、Bloc 等),您可以只使用FutureBuilder
,或者如果您想获取实时数据 Stream,您可以像这样使用StreamBuilder
Streambuilder 示例:
StreamBuilder<QuerySnapshot<Map<String, dynamic>>>( // inside the <> you enter the type of your stream
stream: FirebaseFirestore.instance.collection(user.uid).snapshots(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return ListView.builder(
itemCount: snapshot.data!.docs.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(
snapshot.data!.docs[index].get('title'),
),
);
},
);
}
if (snapshot.hasError) {
return const Text('Error');
} else {
return const CircularProgressIndicator();
}
},
);
我建议您使用数据类而不是data.docs.get('xxx')
。
例如:
class MyDataClass {
final String title;
final String content;
MyDataClass({
required this.title,
required this.content,
});
Map<String, dynamic> toMap() {
final result = <String, dynamic>{};
result.addAll({'title': title});
result.addAll({'content': content});
return result;
}
factory MyDataClass.fromMap(Map<String, dynamic> map) {
return MyDataClass(
title: map['title'] ?? '',
content: map['content'] ?? '',
);
}
String toJson() => json.encode(toMap());
factory MyDataClass.fromJson(String source) => MyDataClass.fromMap(json.decode(source));
}
要生成 toJson/fromJson 或 toMap/fromMap 函数,您可以在 VSCode 或各种网站中使用 Dart 数据 class 生成扩展。
现在您可以像这样显示数据:
if (snapshot.hasData) {
final List<MyDataClass> myList = snapshot.data!.docs
.map(
(doc) => MyDataClass.fromMap(doc.data()),
)
.toList();
return ListView.builder(
itemCount: myList.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(
myList[index].title,
),
);
},
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.