[英]How to list values from documents in Flutter Firestore?
I have a Firebase Firestore build like this:我有一个 Firebase Firestore 构建如下:
I want to pull the title value from all documents in the collection and display this incoming data with ListTile
.我想从集合中的所有文档中提取标题值,并使用
ListTile
显示此传入数据。
I was able to access all the title
values with the code I wrote:我能够使用我编写的代码访问所有
title
值:
FirebaseFirestore.instance.collection(user.uid).get().then((value) {
value.docs.forEach((element) {
print(element.data()["title"]);
});
});
But I don't know how to dump the incoming values to ListTile
.但我不知道如何将传入值转储到
ListTile
。 How can I dump these incoming title values to ListTile
?如何将这些传入的标题值转储到
ListTile
?
If you don't use any state management solution (Riverpod, Provider, Bloc, etc.) you can just use a FutureBuilder
or if you want to get a live data Stream you can use a StreamBuilder
like this如果您不使用任何 state 管理解决方案(Riverpod、Provider、Bloc 等),您可以只使用
FutureBuilder
,或者如果您想获取实时数据 Stream,您可以像这样使用StreamBuilder
Streambuilder Sample: 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();
}
},
);
I recommend you to use Data classes instead of data.docs.get('xxx')
.我建议您使用数据类而不是
data.docs.get('xxx')
。
So for instance:例如:
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));
}
To generate the toJson/fromJson or toMap/fromMap functions you can use the Dart Data class generation extension in VSCode or various websites.要生成 toJson/fromJson 或 toMap/fromMap 函数,您可以在 VSCode 或各种网站中使用 Dart 数据 class 生成扩展。
Now you can display the data just like this:现在您可以像这样显示数据:
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.