如何从开关磁贴更新 Firestore 中的布尔值?

How to update boolean value in Firestore from a switch tile?

我的目标是在 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,
    );
  }
}

您可以改进您的 updateNotifications() 函数以消除重复代码:

 Future<void> updateNotifications() async {

     await FirebaseFirestore.instance
          .collection('userNotifications')
          .doc(currentSignedInUserID)
          .update({
        'messages': notificationsActive,
     });
    
    setState(() {
     notificationsActive = !notificationsActive;
    });
  }

此外,我建议您听听您的 Firestore collection 并根据变化更新 UI。你可以看看如何做到这一点 here.