Reputation: 1079
I am using Google FCM to get notification from back end there are some situation where i am getting called FirebaseMessaging.onMessage.listen
multiple times but after doing some research i have found that there is an issue
after searching for a solution i had no option only option was to do this type of work around
if ((DateTime.now().microsecondsSinceEpoch - _lastOnResumeCall) >
7000000 &&
_lastUniqId != message.data['uniqueId'].toString()) {
_lastUniqId = message.data['uniqueId'].toString();
_lastOnResumeCall = DateTime.now().microsecondsSinceEpoch;
//showing local notification if condition is true
}
but the issue is still remains is there any solution or work around that can be implemented?
This is are the version that i am using currently
Update
// ignore_for_file: avoid_print
import 'dart:io';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:project/api/login_request.dart';
import 'package:project/controller/dashboard.dart';
// import 'package:project/models/remote_message.dart';
import 'package:project/utils/global.dart';
import 'package:project/utils/routes.dart';
class FCMProvider {
static bool gotNewNotification = false;
DashBoardController conttroller = Get.put(DashBoardController());
FirebaseMessaging messaging = FirebaseMessaging.instance;
String? token;
String? notificationId;
GlobalFunctions gf = GlobalFunctions();
String accessToken = "";
String userRoll = "0";
String _lastUniqId = "";
int counte = 0;
int _lastOnResumeCall = 0;
int _lastOnResumeCall2 = 0;
String _lastIdFromshowMessage = "";
int smearphone = 0;
UserAPIRepository userAPIRepository = UserAPIRepository();
stop() {
messaging.unsubscribeFromTopic("all");
}
start() {
if (accessToken.length > 1) messaging.subscribeToTopic("all");
}
initialize() async {
accessToken = await gf.getToken();
userRoll = await gf.getRoleId();
NotificationSettings settings = await messaging.requestPermission(
alert: true,
announcement: false,
badge: true,
carPlay: false,
criticalAlert: false,
provisional: false,
sound: true,
);
token = await messaging.getToken();
await userAPIRepository.setFirebaseToken(token);
messaging.setForegroundNotificationPresentationOptions(
alert: Platform.isAndroid,
badge: true,
sound: true,
);
FirebaseMessaging.onBackgroundMessage(firebaseMessagingBackgroundHandler);
await FirebaseMessaging.instance.getToken();
FirebaseMessaging.onMessage.listen(
(RemoteMessage message) async {
if (message.notification != null) {
// // conttroller.changeTabIndex(2);
// // (DateTime.now().microsecondsSinceEpoch - _lastOnResumeCall) >10000000 &&
// if (_lastUniqId.toString() != message.data['uniqueId'].toString()) {
// }
if (smearphone != 0) {
return;
}
smearphone = 1;
Future.delayed(const Duration(seconds: 1), () {
smearphone = 0;
});
String oldunqi = _lastUniqId;
_lastUniqId = message.data['uniqueId'].toString();
showNotification(
"Last Unqie Id " + oldunqi.toString(),
"Recived Unqiue Id" + _lastUniqId.toString(),
_lastUniqId.toString(),
);
}
},
);
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) async {
if (accessToken.length > 1) {
if (message.data.containsKey("notificationType")) {
if (message.data["notificationType"] == "Message") {
if (userRoll == "5") {
conttroller.changeTabIndex(2);
} else {
conttroller.changeTabIndex(1);
}
} else {
conttroller.changeTabIndex(0);
}
}
// showNotification(message.notification!.title.toString(),
// message.notification!.body.toString());
FCMProvider.gotNewNotification = true;
Get.toNamed(Routes.splash);
}
});
start();
}
showNotification(String title, String message, id, {int type = 0}) {
// Get.dialog(
// AlertDialog(
// title: Text(title),
// content: Text(message),
// actions: <Widget>[
// FlatButton(
// child: Text("Ok"),
// onPressed: () {
// Get.back();
// },
// )
// ],
// ),
// );
Get.showSnackbar(GetSnackBar(
borderRadius: 10,
maxWidth: 250,
margin: const EdgeInsets.only(bottom: 10),
duration: const Duration(seconds: 5),
messageText: Text(
"Varibel checking" +
(_lastIdFromshowMessage.toString() != id.toString()).toString() +
" New id" +
id.toString() +
" Last Id" +
_lastIdFromshowMessage.toString(),
style: const TextStyle(color: Colors.white),
),
));
if (_lastIdFromshowMessage.toString() != id.toString()) {
_lastIdFromshowMessage = id.toString();
Get.snackbar(
title,
message,
duration: const Duration(seconds: 5),
dismissDirection: DismissDirection.horizontal,
boxShadows: const [
BoxShadow(
color: Colors.white,
offset: Offset(0, 0),
),
],
colorText: Colors.black, //kGreen,
);
}
}
}
Future<void> firebaseMessagingBackgroundHandler(RemoteMessage message) async {
print(message.data);
print("Handling a background message: ${message.messageId}");
}
This is pushnotification class
import 'package:portal_del_familiar/controller/bindings/dashboardbind.dart';
import 'package:portal_del_familiar/ui/my_app.dart';
import 'package:flutter/material.dart';
import 'package:get_storage/get_storage.dart';
import 'package:firebase_core/firebase_core.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
await GetStorage.init();
DashboardBinding().dependencies();
runApp(const MyApp());
}
Main.dart
As you can see i am checking another solution also i will update if there is any changes. and i have checked the variables are not updating in condition since the messages are reeving concurrently really appreciate if you can give a way to update the variable before next call is come.
Upvotes: 2
Views: 6834
Reputation: 1079
Okay now i know this is bit lame but i was able to fix the issue. The reason was who ever done code was calling Firebase Messaging init function in 3 places one in Splash screen second login success and in the end when login out so every time it was creating a instance so that way first it's create a instance in splash then in login (that's make 2) then when user logged out and login it's create another instance so every time it's increase one listener so this was the reason so for my solution i have placed init in the main() and removed from every other place and this fixed the issue. @Uni Gandhi Thank you very much for you help on that day.
Upvotes: 3
Reputation: 1
Not happening in my case. I am getting only 1 notification message.
You could try implementing another workaround using a simple integer and displaying the message based on odd/even values.
If you could share your Firebase initialization and OnMessage code then a better solution can be provided.
Upvotes: 0