【发布时间】:2021-07-12 18:32:36
【问题描述】:
我正在尝试使用 Firebase 在我的颤振应用中制作一个最喜欢的按钮。但是当我使用 snapshot.hasData 查看特定项目是否已经存在于收藏列表中时,它总是返回 true,即使该项目不存在于数据库中。所以我尝试了 snapshot.data.exists 并且它有效。但是,即使应用程序运行良好”,它总是在调试控制台中显示以下错误:
The getter 'exists' was called on null.
Receiver: null
Tried calling: exists
我的完整代码:
Widget build(BuildContext context) {
return StreamBuilder<DocumentSnapshot>(
stream: FirebaseFirestore.instance
.collection("UserData")
.doc(_auth.currentUser.uid)
.collection("Favourites")
.doc(widget.items["name"])
.snapshots(),
builder: (context, AsyncSnapshot<DocumentSnapshot> snapshot) {
return Scaffold(
body: Row(
children: [
snapshot.data.exists
? Expanded(
child: TextButton.icon(
onPressed: () {
FirebaseFirestore.instance
.collection("UserData")
.doc(_auth.currentUser.uid)
.collection("Favourites")
.doc(widget.items["name"])
.delete();
},
label: Text(
"Unfavourite Item",
style: TextStyle(
fontWeight: FontWeight.bold,
color: Theme.of(context).accentColor),
),
icon: Icon(
Icons.star,
color: Theme.of(context).accentColor,
),
style: TextButton.styleFrom(
minimumSize: Size.fromHeight(50),
elevation: 0),
),
)
: Expanded(
child: TextButton.icon(
onPressed: () {
FirebaseFirestore.instance
.collection("UserData")
.doc(_auth.currentUser.uid)
.collection("Favourites")
.doc(widget.items["name"])
.set({
"name": widget.items["name"],
"image": widget.items["image"],
"price": widget.items["price"],
"locate": widget.items["locate"],
"assorted": true
});
},
label: Text(
"Favourite Item",
style: TextStyle(
fontWeight: FontWeight.bold,
color: Theme.of(context).accentColor),
),
icon: Icon(
Icons.star_border,
color: Theme.of(context).accentColor,
),
style: TextButton.styleFrom(
minimumSize: Size.fromHeight(50),
elevation: 0),
)),
],
),
);
}
);
}
请帮忙。我是 Flutter 和 Firebase 的新手。
【问题讨论】:
-
确保您的 snapshot.data 包含日期?错误说它为空?试试这个 snapshot.data?.exist
标签: android firebase flutter google-cloud-firestore flutter-test