首页 > 解决方案 > 使用 Flutter 监听 Firestore 中的变化

问题描述

我正在尝试在 Firestore 中收听一个集合,当集合中添加了新文档时,它会通知用户。这是我的代码

class User_Account_Checker extends StatefulWidget {
  const User_Account_Checker({Key? key}) : super(key: key);
  @override
  State<User_Account_Checker> createState() => _User_Account_CheckerState();
}

class _User_Account_CheckerState extends State<User_Account_Checker> {
  FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin=new FlutterLocalNotificationsPlugin();
  User? user= FirebaseAuth.instance.currentUser;
  bool isValid=false;
  bool isLoading=true;
  bool isReady=false;
  
  void initState() {
    var androidInitialize = new AndroidInitializationSettings('@mipmap/ic_launcher');
    var initSetttings = new InitializationSettings(android: androidInitialize);
    flutterLocalNotificationsPlugin.initialize(initSetttings,);
   
    getNotifications();
    checkIfValidUser();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    if(isLoading==true){
  
      return Loading_Screen();
    }else if(isValid==true){
 
      return HomeScreen();
    }else{
   
      return Disabled_Account_Screen();
    }
  }

  void checkIfValidUser() async{ //some code here for user checking if valid user }
  


  void getNotifications()async{
    CollectionReference notification =FirebaseFirestore.instance.collection('Notifications');
    notification.where('notificationFor', isEqualTo: user!.uid).where('isSeen', isEqualTo: false).snapshots().listen((querySnapshot) {
      querySnapshot.docChanges.forEach((changes) async {
        if(changes.type.toString()=="DocumentChangeType.added"){
          print(changes.type.toString());
          showNotification();
        }
      });
    });
  }
  
  showNotification() async {//notifications}
}

但我遇到了一个问题,因为每次应用程序启动时,即使集合中没有发生新的更改,它也会触发通知。请帮我解决我的这个问题。

标签: firebasefluttergoogle-cloud-firestore

解决方案


推荐阅读