push_notifications_initializer.dart 2.1 KB

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