push_notifications_initializer.dart 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import 'package:awesome_notifications/awesome_notifications.dart';
  2. import 'package:cloud_firestore/cloud_firestore.dart';
  3. import 'package:firebase_auth/firebase_auth.dart';
  4. import 'package:firebase_messaging/firebase_messaging.dart';
  5. import 'package:flutter/foundation.dart';
  6. import 'package:flutter/material.dart';
  7. import 'package:physigo/Services/AuthService.dart';
  8. void handleMessages() async {
  9. FirebaseMessaging messaging = FirebaseMessaging.instance;
  10. final _firestore = FirebaseFirestore.instance;
  11. NotificationSettings settings = await messaging.requestPermission(
  12. alert: true,
  13. announcement: false,
  14. badge: true,
  15. carPlay: false,
  16. criticalAlert: false,
  17. provisional: false,
  18. sound: true,
  19. );
  20. localNotificationsSetup();
  21. if (settings.authorizationStatus == AuthorizationStatus.denied) {
  22. return;
  23. }
  24. FirebaseMessaging.onMessage.listen((RemoteMessage message) {
  25. AwesomeNotifications().createNotification(
  26. content: NotificationContent(
  27. id: 10,
  28. channelKey: 'basic_channel',
  29. title: message.notification?.title,
  30. body: message.notification?.body,
  31. color: Colors.blue,
  32. )
  33. );
  34. });
  35. messaging.onTokenRefresh.listen((fcmToken) async {
  36. final fcmToken = await messaging.getToken();
  37. final user = _firestore.collection('Users').doc(FirebaseAuth.instance.currentUser?.uid);
  38. user.update({
  39. 'token': fcmToken,
  40. });
  41. });
  42. }
  43. void localNotificationsSetup() {
  44. AwesomeNotifications().initialize(
  45. // set the icon to null if you want to use the default app icon
  46. null,
  47. [
  48. NotificationChannel(
  49. channelGroupKey: 'basic_channel_group',
  50. channelKey: 'basic_channel',
  51. channelName: 'Basic notifications',
  52. channelDescription: 'Notification channel for basic tests',
  53. )
  54. ],
  55. debug: kDebugMode);
  56. AwesomeNotifications().isNotificationAllowed().then((isAllowed) {
  57. if (!isAllowed) {
  58. // This is just a basic example. For real apps, you must show some
  59. // friendly dialog box before call the request method.
  60. // This is very important to not harm the user experience
  61. AwesomeNotifications().requestPermissionToSendNotifications();
  62. }
  63. });
  64. }