FCM push Notifications

This commit is contained in:
2026-02-25 23:37:08 +08:00
parent 1807dca57d
commit 6ccf820438
9 changed files with 188 additions and 47 deletions
+13 -3
View File
@@ -1,6 +1,7 @@
import 'package:flutter/foundation.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:supabase_flutter/supabase_flutter.dart';
import '../utils/device_id.dart';
import '../models/notification_item.dart';
import 'profile_provider.dart';
@@ -165,10 +166,16 @@ class NotificationsController {
Future<void> registerFcmToken(String token) async {
final userId = _client.auth.currentUser?.id;
if (userId == null) return;
final res = await _client.from('fcm_tokens').insert({
final deviceId = await DeviceId.getId();
// upsert using a unique constraint on (user_id, device_id) so a single
// device keeps its token updated without overwriting other devices.
final payload = {
'user_id': userId,
'device_id': deviceId,
'token': token,
});
'created_at': DateTime.now().toUtc().toIso8601String(),
};
final res = await _client.from('fcm_tokens').upsert(payload);
if (res == null) {
debugPrint(
'registerFcmToken: null response for user=$userId token=$token',
@@ -189,11 +196,14 @@ class NotificationsController {
Future<void> unregisterFcmToken(String token) async {
final userId = _client.auth.currentUser?.id;
if (userId == null) return;
final deviceId = await DeviceId.getId();
// Prefer to delete by device_id to avoid removing other devices' tokens.
final res = await _client
.from('fcm_tokens')
.delete()
.eq('user_id', userId)
.eq('token', token);
.eq('device_id', deviceId)
.or('token.eq.$token');
if (res == null) {
debugPrint(
'unregisterFcmToken: null response for user=$userId token=$token',