Untitled

mail@pastecode.io avatar
unknown
dart
2 years ago
5.3 kB
3
Indexable
Never
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:gaadi_bazaar/data/app_shared_preferences/app_shared_preferences.dart';
import 'package:get/get.dart';

import '../routes.dart';

Future<void> firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  await Firebase.initializeApp();
  print('Handling a background message ${message.messageId}');
  if (message.notification != null) {
    print(message.notification?.title);
    print(message.notification?.body);
    localNotification(message);
  }
}

class FcmNotifications {
  static Future<void> initialise() async {
    AppSharedPreferences _appSharedPreferences =
        Get.put(AppSharedPreferences());
    FirebaseMessaging messaging = FirebaseMessaging.instance;

    var token = await messaging.getToken(); // This Creates a FirebaseToken
    print("Token = $token");
    if (token != null) {
      await _appSharedPreferences.saveFCMToken(token);
    }

//requesting permission from device
    NotificationSettings settings = await messaging.requestPermission(
      alert: true,
      announcement: false,
      badge: true,
      sound: true,
      carPlay: false,
    );
    print("user granted permission: ${settings.authorizationStatus}");

    //if app in terminated state
    RemoteMessage? getInitMessage = await messaging.getInitialMessage();
    if (getInitMessage?.notification != null) {
      localNotification(getInitMessage);
    }

    //if app is background
    FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
      print("On MessageOpenedApp ${message.data}");
      if (message.notification != null) {
        localNotification(message);
      }
    });

    //if app is running on foreground
    FirebaseMessaging.onMessage.listen((RemoteMessage message) {
      print("On Message ${message.notification}");
      localNotification(message);

      // if(event.data["screen"] == 'A'){
      //   Get.to(const ScreenA());
      //   // Navigator.push(context,MaterialPageRoute(builder: (context){return const ScreenA();}) );
      // }
    });

    //if app is terminated or closed
    FirebaseMessaging.onBackgroundMessage(firebaseMessagingBackgroundHandler);
  }
}

localNotification(RemoteMessage? remoteMessage) async {
  try {
    final FlutterLocalNotificationsPlugin _flutterLocalNotificationsPlugin =
        FlutterLocalNotificationsPlugin();
    const AndroidNotificationChannel channel = AndroidNotificationChannel(
      'gadi_bazaar_channel_id', // id
      'gadi_bazaar_channel_name', // title
      description:
          'This channel is used for important notifications.', // description
      importance: Importance.max,
    );

    await _flutterLocalNotificationsPlugin
        .resolvePlatformSpecificImplementation<
            AndroidFlutterLocalNotificationsPlugin>()
        ?.createNotificationChannel(channel);

    AndroidInitializationSettings initializationSettingsAndroid =
        const AndroidInitializationSettings('@mipmap/ic_launcher');
    var initializationSettings = InitializationSettings(
      android: initializationSettingsAndroid,
      // iOS: initializationSettingsIos,
    );
    await _flutterLocalNotificationsPlugin.initialize(initializationSettings,
        onSelectNotification: (String? payload) {
      if (remoteMessage?.data['screen'] == "skip") {
        AppRoutes.goToHomePageWithIndexRemovingAllPreviousScreen(0);
      }
    });

    RemoteNotification? notification = remoteMessage?.notification;
    AndroidNotification? android = remoteMessage?.notification?.android;
    if (notification != null && android != null) {
      await _flutterLocalNotificationsPlugin.show(
          notification.hashCode,
          notification.title,
          notification.body,
          NotificationDetails(
            android: AndroidNotificationDetails(
              channel.id,
              channel.name,
              channelDescription: channel.description,
              icon: '@mipmap/ic_launcher',
              priority: Priority.max,
              importance: Importance.max,
            ),
          ));
    }

//For IOS No set up has been made -----///

  } catch (e) {
    Get.snackbar("Exception", e.toString());
  }
}





    //  AndroidNotificationDetails androidPlatformChannelSpecifics =
    //     AndroidNotificationDetails(
    //   channel.id,
    //   "gadi_bazaar_channel_name",
    //   icon: "@mipmap/ic_launcher",
    //   importance: Importance.max,
    //   priority: Priority.max,
    //   fullScreenIntent: true,
    // );

    //  NotificationDetails platformChannelSpecifics =
    //     NotificationDetails(android: androidPlatformChannelSpecifics);

    // var id = DateTime.now().millisecondsSinceEpoch ~/ 1000;
    // print(id);
    // await _flutterLocalNotificationsPlugin.show(
    //   id,
    //   remoteMessage?.notification?.title,
    //   remoteMessage?.notification?.body,
    //   platformChannelSpecifics,
    //   payload: 'Notification Payload',
    // );