i update flutter_local_notifications into 12.0.3 and show me this error:
error: The named parameter 'onSelectNotification' isn't defined. (undefined_named_parameter at [rosen] lib\services\notification\notification_service.dart:33)
and this is source of file:
import 'dart:convert';
import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:get/get.dart';
import 'package:path_provider/path_provider.dart';
import 'package:rosen/models/models.dart';
import 'package:rosen/screens/screens.dart' show LeaderBoardScreen;
import 'package:rosen/utils/logger.dart';
class NotificationService extends GetxService {
final _notifications = FlutterLocalNotificationsPlugin();
#override
void onInit() {
_initNotifications();
super.onInit();
}
Future<void> _initNotifications() async {
const androidInitializationSettings =
AndroidInitializationSettings('#drawable/app_notification_icon');
const iosInitializationSettings = DarwinInitializationSettings(
requestAlertPermission: false,
requestSoundPermission: false,
requestBadgePermission: false,
);
const InitializationSettings initializationSettings =
InitializationSettings(
android: androidInitializationSettings,
iOS: iosInitializationSettings);
_notifications.initialize(initializationSettings,
onSelectNotification: (payload) {
if (payload != null) {
final QuizPaperModel quizPaperModel =
QuizPaperModel.fromJson(json.decode(payload));
Get.toNamed(LeaderBoardScreen.routeName, arguments: quizPaperModel);
//MyApp.navigatorKey.currentState!.pushNamed(LeaderBoardScreen.routeName, arguments:quizPaperModel);
}
});
}
Future<void> showQuizCompletedNotification(
{required int id,
String? title,
String? body,
String? imageUrl,
String? payload}) async {
BigPictureStyleInformation? bigPictureStyleInformation;
String? largeIconPath;
if (imageUrl != null) {
largeIconPath = await _downloadAndSaveFile(imageUrl, 'largeIcon');
final String? bigPicturePath =
await _downloadAndSaveFile(imageUrl, 'bigPicture');
if (bigPicturePath != null) {
bigPictureStyleInformation = BigPictureStyleInformation(
FilePathAndroidBitmap(bigPicturePath),
hideExpandedLargeIcon: true,
contentTitle: '<b>$title</b>',
htmlFormatContentTitle: true,
summaryText: '<b>$body</b>',
htmlFormatSummaryText: true);
}
}
_notifications.show(
id,
title,
body,
NotificationDetails(
android: AndroidNotificationDetails('quizcomplete', 'quizcomplete',
channelDescription: 'Open leaderboard',
importance: Importance.max,
largeIcon: FilePathAndroidBitmap(largeIconPath!),
styleInformation: bigPictureStyleInformation,
priority: Priority.max),
iOS: const DarwinNotificationDetails(
presentAlert: true, presentBadge: true, presentSound: true)),
payload: payload);
}
Future<String?> _downloadAndSaveFile(String url, String fileName) async {
try {
final Directory directory = await getApplicationDocumentsDirectory();
final String filePath = '${directory.path}/$fileName';
final http.Response response = await http.get(Uri.parse(url));
final File file = File(filePath);
await file.writeAsBytes(response.bodyBytes);
return filePath;
} catch (e) {
AppLogger.e(e);
}
return null;
}
}
i try to define parameter but failed because still learning flutter
how i can solve this problem?
Since the version 10.0.0: onSelectNotification has been changed to onDidReceiveNotificationResponse as mentioned in the ChangeLog.md:
onDidReceiveNotificationResponse: invoked only when the app is running. This works for when a user has selected a notification or notification action. This replaces the onSelectNotification callback that existed before.
Related
I'm trying to include local notifications in my Flutter project using the latest version flutter_local_notifications: ^13.0.0, and I have this error:
The argument type 'Future Function(String?)' can't be assigned to the parameter type 'void Function(NotificationResponse)?
onDidReceiveNotificationResponse : onSelectNotification
This is my class:
class LocalNotificationService {
LocalNotificationService();
final _localNotificationService = FlutterLocalNotificationsPlugin();
final BehaviorSubject<String?> onNotificationClick = BehaviorSubject();
Future<void> initialize() async {
tz.initializeTimeZones();
const AndroidInitializationSettings androidInitializationSettings =
AndroidInitializationSettings('#drawable/ic_stat_android');
DarwinInitializationSettings iosInitializationSettings =
DarwinInitializationSettings(
requestAlertPermission: true,
requestBadgePermission: true,
requestSoundPermission: true,
onDidReceiveLocalNotification: onDidReceiveLocalNotification,
);
final InitializationSettings settings = InitializationSettings(
android: androidInitializationSettings,
iOS: iosInitializationSettings,
);
await _localNotificationService.initialize(
settings,
onDidReceiveNotificationResponse : onSelectNotification, //here is the error
);
}
Future<NotificationDetails> _notificationDetails() async {
const AndroidNotificationDetails androidNotificationDetails =
AndroidNotificationDetails('channel_id', 'channel_name',
channelDescription: 'description',
importance: Importance.max,
priority: Priority.max,
playSound: true);
const DarwinNotificationDetails iosNotificationDetails =
DarwinNotificationDetails();
return const NotificationDetails(
android: androidNotificationDetails,
iOS: iosNotificationDetails,
);
}
Future<void> showNotification({
required int id,
required String title,
required String body,
}) async {
final details = await _notificationDetails();
await _localNotificationService.show(id, title, body, details);
}
Future<void> showScheduledNotification(
{required int id,
required String title,
required String body,
required int seconds}) async {
final details = await _notificationDetails();
await _localNotificationService.zonedSchedule(
id,
title,
body,
tz.TZDateTime.from(
DateTime.now().add(Duration(seconds: seconds)),
tz.local,
),
details,
androidAllowWhileIdle: true,
uiLocalNotificationDateInterpretation:
UILocalNotificationDateInterpretation.absoluteTime,
);
}
Future<void> showNotificationWithPayload(
{required int id,
required String title,
required String body,
required String payload}) async {
final details = await _notificationDetails();
await _localNotificationService.show(id, title, body, details,
payload: payload);
}
void onDidReceiveLocalNotification(
int id, String? title, String? body, String? payload) {
print('id $id');
}
Future<void> onSelectNotification(String? payload) async {
print('payload $payload');
if (payload != null && payload.isNotEmpty) {
onNotificationClick.add(payload);
}
}
}
What I'm missing?
onDidReceiveNotificationResponse provide NotificationResponse on callback. You can get payload like
onDidReceiveNotificationResponse: (details) =>
onSelectNotification(details.payload),
Or
Future<void> onSelectNotification(NotificationResponse? response) async {
print('payload $response');
if (response?.payload != null && response!.payload!.isNotEmpty) {
onNotificationClick.add(response.payload);
}
}
And this will be used onDidReceiveNotificationResponse : onSelectNotification.
I tried to download an image when push notification is coming. When application is opened this feature is work fine, but when application is closed I can't download the image and got this error :
MissingPluginException(No implementation found for method getApplicationDocumentsDirectory on channel plugins.flutter.io/path_provider)
I've tried to register the path provider in MainActivity but doesn't work.
Here are sample of my code
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
logger.d("Handling a background message: ${message.data}");
if (message.data != null) {
final data = message.data;
final title = data['title'];
final body = data['content'];
await CustomLocalNotification.showNotification(title, body, data['type'], data['image']);
}
return Future<void>.value();
}
There is an image that i try to download and show it on push notification. And here is the code to download and handle push notification
static Dio dio = DioUtil.instance(baseUrl:"" );
static Future<String> _downloadAndSaveFile(String url, String fileName) async {
final Directory directory = Platform.isIOS?await getApplicationSupportDirectory(): await getApplicationDocumentsDirectory();
final String filePath = Platform.isIOS?'${directory.path}/$fileName.jpg': '${directory.path}/$fileName';
final response = await dio.get(url, options: Options(
responseType: ResponseType.bytes,
followRedirects: false,
validateStatus: (status) { return status < 500; }
),);
final File file = File(filePath);
if(Platform.isIOS){
final imageBytes = response.data;
final bytes = imageBytes.buffer.asUint8List();
await file.writeAsBytes(bytes);
}else{
var raf = file.openSync(mode: FileMode.write);
raf.writeFromSync(response.data);
await raf.close();
}
return filePath;
}
static Future<void> showNotification(String title, String body, String type, String images,) async {
StyleInformation styleInformation;
IOSNotificationDetails iosNotificationDetails;
if((type==NotificationType.Promo.title || type == NotificationType.News.title) && images !=""){
final String largeIconPath = await _downloadAndSaveFile(
'$images', 'largeIcon');
styleInformation = BigPictureStyleInformation(FilePathAndroidBitmap(largeIconPath),
contentTitle: '$type',
htmlFormatContentTitle: true,
summaryText: '$title',
htmlFormatSummaryText: true
);
iosNotificationDetails =
IOSNotificationDetails(attachments: <IOSNotificationAttachment>[
IOSNotificationAttachment(largeIconPath),
]);
}else{
styleInformation = DefaultStyleInformation(true, true);
iosNotificationDetails =
IOSNotificationDetails();
}
AndroidNotificationDetails androidPlatformChannelSpecifics = AndroidNotificationDetails(
'xx',
'xx_channel_name',
channelDescription: 'xx_channel_description',
importance: Importance.max,
priority: Priority.high,
ticker: 'ticker',
styleInformation: styleInformation
);
NotificationDetails platformChannelSpecifics = NotificationDetails(android: androidPlatformChannelSpecifics, iOS: iosNotificationDetails);
await flutterLocalNotificationsPlugin.show(0, '$type', '$title', platformChannelSpecifics);
}
}
Seems i got error in this line :
final Directory directory = Platform.isIOS?await getApplicationSupportDirectory(): await getApplicationDocumentsDirectory();
Could you please suggest me how to fix this. I Thank you.
Register path provider in MainActivity look like this
override fun registerWith(registry: PluginRegistry) {
io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin.registerWith(registry?.registrarFor("io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin"));
PathProviderPlugin.registerWith(registry.registrarFor("io.flutter.plugins.pathprovider.PathProviderPlugin"))
}
but it doesn't work
I have updated the pods in my app. And now I have some errors. I have been able to fix few of them, but I still have two where I do not find what I should do. Please, can you help? Thank you.
I am using flutter_local_notifications: ^10.0.0
The other errors have been fixed. I guess that I should not have updated the files, but my objective was to fix a buffer overflow problem.
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:rxdart/rxdart.dart';
import 'package:timezone/data/latest.dart' as tz;
import 'package:timezone/timezone.dart' as tz;
import 'package:flutter_native_timezone/flutter_native_timezone.dart';
class NotificationApi {
static final _notifications = FlutterLocalNotificationsPlugin();
static final onNotifications = BehaviorSubject<String?>();
static Future _notificationDetails() async {
const sound = 'notification_sound.wav';
return NotificationDetails(
android: AndroidNotificationDetails(
'channel id 8',
'channel name',
channelDescription: 'channel description',
importance: Importance.max,
//playSound: false,
sound: RawResourceAndroidNotificationSound(sound.split('.').first),
enableVibration: false,
// styleInformation: styleInformation,
),
iOS: const DarwinNotificationDetails(
presentSound: false,
sound: sound,
),
);
}
static Future init({bool initScheduled = false}) async {
const android = AndroidInitializationSettings('#mipmap/ic_launcher');
const iOS = DarwinInitializationSettings();
const settings = InitializationSettings(android: android, iOS: iOS);
/// Handle payload when app is closed
final details = await _notifications.getNotificationAppLaunchDetails();
if (details != null && details.didNotificationLaunchApp) {
onNotifications.add(details.payload); ///ERROR (The named parameter 'onSelectNotification' isn't defined.)
}
await _notifications.initialize(
settings,
onSelectNotification: (payload) async {
onNotifications.add(payload); ///ERROR (The getter 'payload' isn't defined for the type 'NotificationAppLaunchDetails'.)
},
);
if (initScheduled) {
tz.initializeTimeZones();
final locationName = await FlutterNativeTimezone.getLocalTimezone();
tz.setLocalLocation(tz.getLocation(locationName));
}
}
/// Direct Notification
static Future showNotification({
int id = 0,
String? title,
String? body,
String? payload,
}) async =>
_notifications.show(
id,
title,
body,
await _notificationDetails(),
payload: payload,
);
/// Notification for specific DateTime
static void showScheduledNotification({
int? id ,
String? title,
String? body,
String? payload,
required DateTime scheduledDate,
}) async =>
_notifications.zonedSchedule(
id!,
title,
body,
tz.TZDateTime.from(scheduledDate, tz.local),
await _notificationDetails(),
payload: payload,
androidAllowWhileIdle: true,
uiLocalNotificationDateInterpretation:
UILocalNotificationDateInterpretation.absoluteTime,
);
static tz.TZDateTime _scheduleDaily(Time time) {
final now = tz.TZDateTime.now(tz.local);
final scheduledDate = tz.TZDateTime(tz.local, now.year, now.month, now.day,
time.hour, time.minute, time.second);
return scheduledDate.isBefore(now)
? scheduledDate.add(const Duration(days: 1))
: scheduledDate;
}
static List<tz.TZDateTime> _scheduleWeekly(Time time,
{required List<int> days}) {
return days.map((day) {
tz.TZDateTime scheduledDate = _scheduleDaily(time);
while (day != scheduledDate.weekday) {
scheduledDate = scheduledDate.add(const Duration(days: 1));
}
return scheduledDate;
}).toList();
}
static void cancel(int id) => _notifications.cancel(id);
static void cancelAll() => _notifications.cancelAll();
static int convertStringToHash (String id) {
int notificationId = id.hashCode;
return notificationId;
}
}
I need to make like this notification
My Output code
my Pubspec.yaml file. I am using latest version of flutter_local_notifications
flutter_local_notifications: ^9.2.0
This is my Notification Controller code
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/services.dart';
import 'package:http/http.dart' as http;
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:image/image.dart' as image;
import 'package:path_provider/path_provider.dart';
class NotificationService {
static final NotificationService _notificationService =
NotificationService._internal();
final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
factory NotificationService() {
return _notificationService;
}
NotificationService._internal();
Future<void> init(
Function(int, String?, String?, String?)?
onDidReceiveLocalNotification) async {
const AndroidInitializationSettings initializationSettingsAndroid =
AndroidInitializationSettings('#mipmap/launcher_icon');
final IOSInitializationSettings initializationSettingsIOS =
IOSInitializationSettings(
requestAlertPermission: false,
requestBadgePermission: false,
requestSoundPermission: false,
onDidReceiveLocalNotification:
(int id, String? title, String? body, String? payload) async {},
);
final InitializationSettings initializationSettings =
InitializationSettings(
android: initializationSettingsAndroid,
iOS: initializationSettingsIOS,
);
await flutterLocalNotificationsPlugin.initialize(
initializationSettings,
onSelectNotification: (String? payload) async {
if (payload != null) {
print('notification payload: $payload');
}
},
);
}
Future selectNotification(String? payload) async {
print('selectNotification: $payload');
}
Future<String> _downloadAndSaveFile(String url, String fileName) async {
final Directory? directory = await getExternalStorageDirectory();
final String filePath = '${directory!.path}/$fileName.png';
final http.Response response = await http.get(Uri.parse(url));
final File file = File(filePath);
await file.writeAsBytes(response.bodyBytes);
return filePath;
}
Future showNotify({
required String body,
required String image,
}) async {
final String largeIconPath = await _downloadAndSaveFile(
'https://via.placeholder.com/48x48',
'largeIcon',
);
final String bigPicturePath = await _downloadAndSaveFile(
image,
'bigPicture',
);
await flutterLocalNotificationsPlugin.show(
123,
'New Buisness Sutra Updated',
body,
NotificationDetails(
android: AndroidNotificationDetails(
'big text channel id',
'big text channel name',
ongoing: true,
priority: Priority.max,
largeIcon: FilePathAndroidBitmap(largeIconPath),
channelDescription: 'big text channel description',
styleInformation: BigPictureStyleInformation(
FilePathAndroidBitmap(bigPicturePath),
hideExpandedLargeIcon: false,
contentTitle: 'overridden <b>big</b> content title',
htmlFormatContentTitle: true,
summaryText: 'summary <i>text</i>',
htmlFormatSummaryText: true,
),
),
),
payload: 'data',
);
}
}
I initialized the firebase and notification on my main.dart file
void main() async {
WidgetsFlutterBinding.ensureInitialized();
if (!kIsWeb) {
await Firebase.initializeApp();
firebaseCloudMessagingListeners();
await NotificationService().init();
}
runApp(const MyApp());
}
firebaseCloudMessagingListeners() {
FirebaseMessaging.onBackgroundMessage(_messageHandler);
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
print(message);
_messageHandler(message);
});
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
print("Message opened");
});
}
Future<void> _messageHandler(RemoteMessage message) async {
Map<String, dynamic> data = message.data;
print(data);
await NotificationService().showNotify(
body: data["body"],
image: data["image"],
);
}
The firebase_messaging plugin works fine. The problem is with the big picture on the notification from flutter_local_notifications.
I download the image by using path_provider and http. also this image succesfully downloaded on my app External storage directory. But not shown on the notification
/storage/emulated/0/Android/data/in.myapp.dhrona/files/largeIcon.png
/storage/emulated/0/Android/data/in.myapp.dhrona/files/bigIcon.png
Any solutions for this issue
To show network image,
final http.Response response = await http.get(Uri.parse(URL));
BigPictureStyleInformation bigPictureStyleInformation =
BigPictureStyleInformation(
ByteArrayAndroidBitmap.fromBase64String(base64Encode(image)),
largeIcon: ByteArrayAndroidBitmap.fromBase64String(base64Encode(image)),
);
flutterLocalNotificationsPlugin.show(
Random().nextInt(1000),
title,
description,
NotificationDetails(
android: AndroidNotificationDetails(channel.id, channel.name,
channelDescription: channel.description,
importance: Importance.high,
styleInformation: bigPictureStyleInformation),
),
);
To show local image,
final String filePath = '${directory.path}/$fileName';
final BigPictureStyleInformation bigPictureStyleInformation =
BigPictureStyleInformation(FilePathAndroidBitmap(filePath),
largeIcon: FilePathAndroidBitmap(filePath));
flutterLocalNotificationsPlugin.show(
Random().nextInt(1000),
title,
description,
NotificationDetails(
android: AndroidNotificationDetails(channel.id, channel.name,
channelDescription: channel.description,
importance: Importance.high,
styleInformation: bigPictureStyleInformation),
),
);
With AwesomeNotifications I don't need to download. I just give the url like below:
Future<void> showNotificationChatMessage(
RemoteMessage message, MyMessage myMessage) async {
final chatId = message.data['chatId'];
NotificationContent? notificationContent;
if (myMessage.type == MyMessageType.text ||
myMessage.replyType == MyMessageReplyType.text) {
notificationContent = NotificationContent(
id: 10,
channelKey: 'basic_channel',
title: message.data['title'].toString(),
body: message.data['body'].toString(),
payload: {'chatId': chatId.toString()});
} else if (myMessage.type == MyMessageType.image ||
myMessage.replyType == MyMessageReplyType.image) {
notificationContent = NotificationContent(
id: 11,
channelKey: 'big_picture',
title: message.data['title'].toString(),
body: 'Image',
bigPicture: myMessage.message,
showWhen: true,
displayOnBackground: true,
payload: {'chatId': chatId.toString()},
notificationLayout: NotificationLayout.BigPicture);
}
if (notificationContent != null) {
AwesomeNotifications().createNotification(content: notificationContent);
}
}
Although the answer by #Vignesh works, here are some improvements to that answer:
response is not used in the example
there is no need to set the "largeIcon" property with the same image data as the big image because it will show the same image two times in the notification when the notification is expanded.
the final answer should look like this:
final http.Response response = await http.get(Uri.parse(imageUrl));
bigPictureStyleInformation = BigPictureStyleInformation(
ByteArrayAndroidBitmap.fromBase64String(base64Encode(response.bodyBytes)));
flutterLocalNotificationsPlugin.show(
notification.hashCode,
notification.title ?? 'APP_NAME',
notification.body,
NotificationDetails(
android: AndroidNotificationDetails(
channel.id,
channel.name,
channelDescription: channel.description,
styleInformation: bigPictureStyleInformation,
// other properties...
),
)
);
Before switching to Flutter 2, I was using an old version of firebaseMessaging without problems, and now I have the latest version.After upgrading I get the following error:
The class 'FirebaseMessaging' doesn't have a default constructor.
And:
The method 'configure' isn't defined for the type 'FirebaseMessaging'.
Full class:
class ShowNotifications {
static final FirebaseMessaging firebaseMessaging = FirebaseMessaging();
static FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
new FlutterLocalNotificationsPlugin();
static void initialization(){
var initializationSettingsAndroid =
new AndroidInitializationSettings('#mipmap/ic_launcher');
var initializationSettingsIOS = new IOSInitializationSettings();
var initializationSettings = new InitializationSettings(
android: initializationSettingsAndroid, iOS: initializationSettingsIOS);
flutterLocalNotificationsPlugin = new FlutterLocalNotificationsPlugin();
flutterLocalNotificationsPlugin.initialize(initializationSettings,
onSelectNotification: onSelectNotification);
}
static void showNotification(String title, String body) async {
await _demoNotification(title, body);
}
static Future<void> _demoNotification(String title, String body) async {
var androidPlatformChannelSpecifics = AndroidNotificationDetails(
'channel_ID', 'channel name', 'channel description',
importance: Importance.max,
playSound: true,
// sound: 'sound',
// sound: true,
showProgress: true,
priority: Priority.high,
ticker: 'test ticker');
var iOSChannelSpecifics = IOSNotificationDetails();
var platformChannelSpecifics = NotificationDetails(
android: androidPlatformChannelSpecifics, iOS: iOSChannelSpecifics);
await flutterLocalNotificationsPlugin
.show(0, title, body, platformChannelSpecifics, payload: 'test');
}
static Future onSelectNotification(String payload) async {
showDialog(
// context: context,
builder: (_) {
return new AlertDialog(
title: Text("PayLoad"),
content: Text("Payload : $payload"),
);
},
);
}
static notification(){
firebaseMessaging.configure(
onMessage: (Map<String, dynamic> message) async {
showNotification(message['notification']['title'], message['notification']['body']);
// print("onMessage: $message");
},
onLaunch: (Map<String, dynamic> message) async {
print("onLaunch: $message");
},
onResume: (Map<String, dynamic> message) async {
print("onResume: $message");
},
);
}
}
I was able to control this class from all the application pages.
What do I need to change with the new version. So that I can use the class as it was in the past.
Try to update your firebase_messaging package and also take care to use compatile packages for the other Firebase SDKs. I would recommend to copy the ones from the official documentation for each one you use.
Here is a full example how the new Firebase Messaging SDK would work with the new API:
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:fluttertoast/fluttertoast.dart';
import '../constants.dart';
FirebaseMessaging messaging = FirebaseMessaging.instance;
final _database = FirebaseDatabase.instance;
final _firestore = FirebaseFirestore.instance;
final _auth = FirebaseAuth.instance;
class MessagingService {
static bool showToast = true;
static String currentToken;
static void initialize() async {
await messaging.requestPermission(
alert: true,
announcement: false,
badge: true,
carPlay: false,
criticalAlert: false,
provisional: false,
sound: true,
);
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
if (message.notification != null) {
print('Message also contained a notification: ${message.notification}');
}
if (showToast && message.notification != null) {
Fluttertoast.showToast(
msg: "${message.notification.title}: ${message.notification.body} ",
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.BOTTOM,
timeInSecForIosWeb: 1,
//backgroundColor: Colors.red,
//textColor: Colors.white,
fontSize: 16.0,
);
}
});
messaging.onTokenRefresh.listen((String token) async {
await syncToken();
});
await syncToken();
}
static Future<String> getToken() async {
String token = await messaging.getToken();
return token;
}
static Future syncToken() async {
try {
String token = await messaging.getToken();
if (token != currentToken) {
if (syncDatabase == databases.RealtimeDatabase) {
await _database
.reference()
.child(
'$kNotificationTokensSyncBasePath${_auth.currentUser.uid}/$token')
.set(true);
} else {
await _firestore
.doc('$kNotificationTokensSyncBasePath${_auth.currentUser.uid}')
.set({'$token': true}, SetOptions(merge: true));
}
currentToken = token;
}
} catch (e) {
print(e);
}
return;
}
static Future unsyncToken(User user) async {
try {
String token = await messaging.getToken();
if (syncDatabase == databases.RealtimeDatabase) {
await _database
.reference()
.child('$kNotificationTokensSyncBasePath${user.uid}/$token')
.set(null);
} else {
await _firestore
.doc('$kNotificationTokensSyncBasePath${_auth.currentUser.uid}')
.set({'$token': FieldValue.delete()}, SetOptions(merge: true));
}
currentToken = null;
} catch (e) {
print(e);
}
return;
}
}