![](/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.