firebase - 使用 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}
}
但我遇到了一个问题,因为每次应用程序启动时,即使集合中没有发生新的更改,它也会触发通知。请帮我解决我的这个问题。
解决方案
推荐阅读
- arrays - Minzinc:对二维数组的每一行应用约束
- c# - SignalR:通知从 ASP.NET Core Web API 到 Angular 7 客户端的冗长操作的进度
- python - 如何检测python中的边缘缺陷?
- r - R Mosek 使用二次规划
- machine-learning - 我的 CNN 模型的权重没有完全打印出来
- ios - Xamarin 窗体 iOS WebRTC
- android - 如何更改应用背景的标题颜色?
- python - 在docker中第二次运行时如何修复硒?
- mule - 如何将多个输入参数添加到 Mule 中的数据库连接器
- javascript - 如何修复反应 Heroku 中的 130 反应错误?