我已經查看了幾篇關于更新 Firestore 資料庫中布林值的不同 SO 帖子,還查看了幾篇在 Google 搜索中發現的文章。SO 帖子和文章都相對簡單,我目前能夠從 Firestore 獲得所需的確切行為,而不會出現任何錯誤。
我的目標是在 Firestore 中有一個 userNotifications 集合,用于跟蹤用戶通知首選項。用戶可以通過點擊開關磁貼在真偽之間切換。使用下面的代碼,Firestore 會根據用戶互動立即正確地更新布林值,并且用戶界面正在更新并反映更改。如果用戶注銷并重新登錄,布林值會準確地反映在用戶界面中。
在我在代碼中更廣泛地應用這種方法之前,我希望有人可以發表評論并讓我知道我在 Firestore 中更新布林值的方法是否有效,或者為我指出一個更好的方向,以便我可以改進我的代碼。SO帖子或檔案的鏈接很好,因為我非常愿意閱讀和學習。提前感謝您的幫助。
class NotificationsMessagesTile extends StatefulWidget {
const NotificationsMessagesTile({
Key? key,
}) : super(key: key);
@override
State<NotificationsMessagesTile> createState() =>
_NotificationsMessagesTileState();
}
class _NotificationsMessagesTileState extends State<NotificationsMessagesTile> {
bool notificationsActive = false;
final String? currentSignedInUserID = Auth().currentUser?.uid;
Future<void> updateNotifications() async {
if (!notificationsActive) {
notificationsActive = true;
FirebaseFirestore.instance
.collection('userNotifications')
.doc(currentSignedInUserID)
.update({
'messages': false,
});
} else {
notificationsActive = false;
FirebaseFirestore.instance
.collection('userNotifications')
.doc(currentSignedInUserID)
.update({
'messages': true,
});
}
setState(() {});
}
@override
Widget build(BuildContext context) {
return SwitchListTileSliver(
icon: Provider.of<NotificationsPageProvider>(context).areMessagesTurnedOn
? Icons.notifications_active
: Icons.notifications_off,
onChanged: (bool value) {
final provider = Provider.of<NotificationsPageProvider>(
context,
listen: false,
);
provider.updateMessagesSettings(isOn: value);
updateNotifications();
},
subTitle:
Provider.of<NotificationsPageProvider>(context).areMessagesTurnedOn
? const Text(
SettingsPageString.messagesOn,
)
: const Text(
SettingsPageString.messagesOff,
),
title: SettingsPageString.messages,
value:
Provider.of<NotificationsPageProvider>(context).areMessagesTurnedOn,
);
}
}
uj5u.com熱心網友回復:
您可以改進您的updateNotifications()功能,使其沒有重復的代碼:
Future<void> updateNotifications() async {
await FirebaseFirestore.instance
.collection('userNotifications')
.doc(currentSignedInUserID)
.update({
'messages': notificationsActive,
});
setState(() {
notificationsActive = !notificationsActive;
});
}
我還建議您收聽您的 Firestore 收藏并在更改時更新 UI。你可以在這里查看如何做到這一點。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/409785.html
標籤:
