Created
January 25, 2023 09:53
-
-
Save AmolPardeshi99/6c39c193eaa563639d4c737847cfc6dc to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:convert'; | |
import 'package:firebase_core/firebase_core.dart'; | |
import 'package:firebase_messaging/firebase_messaging.dart'; | |
import 'package:flutter/foundation.dart'; | |
import 'package:flutter/material.dart'; | |
import 'package:flutter_local_notifications/flutter_local_notifications.dart'; | |
import 'package:get/get.dart'; | |
import 'package:leap_counsellor_chat_and_call_app/sendbird/color.dart'; | |
import 'package:leap_counsellor_chat_and_call_app/sendbird/components/push_notification.dart'; | |
import 'package:leap_counsellor_chat_and_call_app/sendbird/main_binding.dart'; | |
import 'package:leap_counsellor_chat_and_call_app/sendbird/routes.dart'; | |
import 'package:leap_counsellor_chat_and_call_app/sendbird/util/notification_service.dart'; | |
import 'package:notification_permissions/notification_permissions.dart'; | |
import 'package:universal_io/io.dart'; | |
import 'Constants/SharedPreferencehelper.dart'; | |
Future _firebaseMessagingBackgroundHandler(RemoteMessage message) async { | |
print("Handling background message: ${message.messageId}"); | |
String? channelUrl = null; | |
if (message.data.containsKey('sendbird')) { | |
final sendBird = json.decode(message.data['sendbird']); | |
final channel = sendBird['channel']; | |
channelUrl = channel['channel_url']; | |
final sender = sendBird['sender']; | |
NotificationService.showNotification( | |
sender['name'] ?? '', | |
sendBird['message'] ?? '', | |
); | |
} | |
} | |
late String permissionStatusFuture; | |
var permGranted = "granted"; | |
var permDenied = "denied"; | |
var permUnknown = "unknown"; | |
var permProvisional = "provisional"; | |
Future<void> checkPNPermissions() async { | |
permissionStatusFuture = await getCheckNotificationPermStatus(); | |
if (permissionStatusFuture != permGranted) { | |
// show the dialog/open settings screen | |
NotificationPermissions.requestNotificationPermissions( | |
iosSettings: const NotificationSettingsIos( | |
sound: true, badge: true, alert: true)) | |
.then((_) async { | |
// when finished, check the permission status | |
permissionStatusFuture = await getCheckNotificationPermStatus(); | |
if (permissionStatusFuture != permGranted) {} | |
}); | |
} | |
} | |
Future<String> getCheckNotificationPermStatus() { | |
return NotificationPermissions.getNotificationPermissionStatus() | |
.then((status) { | |
switch (status) { | |
case PermissionStatus.denied: | |
return permDenied; | |
case PermissionStatus.granted: | |
return permGranted; | |
case PermissionStatus.unknown: | |
return permUnknown; | |
case PermissionStatus.provisional: | |
return permProvisional; | |
default: | |
return permUnknown; | |
} | |
}); | |
} | |
Future<void> main() async { | |
WidgetsFlutterBinding.ensureInitialized(); | |
await checkPNPermissions(); | |
//Use DefaultFirebaseOptions to allow web app | |
await Firebase.initializeApp(); | |
await SharedPrefs.instance.init(); | |
return runApp(const MyApp()); | |
} | |
final appState = AppState(); | |
class AppState with ChangeNotifier { | |
bool didRegisterToken = false; | |
String? token; | |
String? destChannelUrl; | |
void setDestination(String? channelUrl) { | |
destChannelUrl = channelUrl; | |
notifyListeners(); | |
} | |
} | |
const AndroidNotificationChannel channel = AndroidNotificationChannel( | |
'high_importance_channel', // id | |
'High Importance Notifications', // title | |
description: | |
'This channel is used for important notifications.', // description | |
importance: Importance.high, | |
playSound: true, | |
); | |
final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = | |
FlutterLocalNotificationsPlugin(); | |
class MyApp extends StatefulWidget { | |
const MyApp({Key? key}) : super(key: key); | |
@override | |
MyAppState createState() => MyAppState(); | |
} | |
class MyAppState extends State<MyApp> { | |
late int _totalNotifications; | |
late final FirebaseMessaging _messaging; | |
PushNotification? _notificationInfo; | |
// [Push Notification Set Up] | |
void requestAndRegisterNotification() async { | |
// Initialize the Firebase app | |
await Firebase.initializeApp(); | |
// Instantiate Firebase Messaging | |
_messaging = FirebaseMessaging.instance; | |
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler); | |
// To enable foreground notification in firebase messaging for IOS | |
await FirebaseMessaging.instance | |
.setForegroundNotificationPresentationOptions( | |
alert: true, // Required to display a heads up notification | |
badge: true, | |
sound: true, | |
); | |
// On iOS, this helps to take the user permissions | |
NotificationSettings settings = await _messaging.requestPermission( | |
alert: true, | |
badge: true, | |
provisional: false, | |
sound: true, | |
); | |
if (settings.authorizationStatus == AuthorizationStatus.authorized) { | |
print('User granted permission'); | |
String? token; | |
if (Platform.isIOS) { | |
//Retrieve pushtoken for IOS | |
token = await _messaging.getAPNSToken(); | |
} else { | |
// Retrieve pushtoken for FCM | |
token = await _messaging.getToken(); | |
} | |
print("SAVING FCM TOKEN TO SERVER = $token"); | |
await SharedPrefs.instance.setString(SharedPrefs.FCM_TOKEN, token!); | |
appState.token = token; | |
// For handling the received notifications | |
FirebaseMessaging.onMessage.listen((RemoteMessage message) { | |
print('title: ${message.notification?.title}'); | |
print('body: ${message.notification?.body}'); | |
// Parse the message received | |
PushNotification notification = PushNotification( | |
title: message.notification?.title, | |
body: message.notification?.body, | |
); | |
setState(() { | |
_notificationInfo = notification; | |
_totalNotifications++; | |
}); | |
if (_notificationInfo != null) { | |
NotificationService.showNotification( | |
_notificationInfo?.title ?? '', _notificationInfo?.body ?? ''); | |
} | |
}); | |
} else { | |
print('User declined or has not accepted permission'); | |
} | |
} | |
@override | |
void initState() { | |
requestAndRegisterNotification(); | |
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) { | |
PushNotification notification = PushNotification( | |
title: message.notification?.title, | |
body: message.notification?.body, | |
); | |
setState(() { | |
_notificationInfo = notification; | |
_totalNotifications++; | |
}); | |
}); | |
_totalNotifications = 0; | |
super.initState(); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return GetMaterialApp( | |
theme: ThemeData( | |
primaryColor: appPrimaryColor, | |
), | |
debugShowCheckedModeBanner: false, | |
title: 'Leap Counsellor App', | |
initialRoute: "/RootRoute", | |
getPages: routes, | |
initialBinding: MainBinding(), | |
); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment