Skip to content

Commit 6ed2b39

Browse files
author
Saksham-flutter
committed
Notification Handler Added
1 parent 1d7343b commit 6ed2b39

File tree

5 files changed

+258
-76
lines changed

5 files changed

+258
-76
lines changed
Lines changed: 188 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,188 @@
1+
import 'dart:convert';
2+
import 'dart:developer';
3+
import 'dart:io';
4+
5+
import 'package:firebase_core/firebase_core.dart';
6+
import 'package:firebase_messaging/firebase_messaging.dart';
7+
import 'package:flutter/material.dart';
8+
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
9+
import 'package:mvc_flutter/my_app/my_app.dart';
10+
11+
@pragma('vm:entry-point')
12+
Future<void> firebaseMessagingBackgroundHandler(
13+
RemoteMessage remoteMessage) async {
14+
await NotificationHandler.initialize();
15+
log(remoteMessage.data.toString(), name: "Background Notification");
16+
17+
///TODO Handling Background Message Notification
18+
}
19+
20+
@pragma('vm:entry-point')
21+
void didReceiveBackgroundNotificationResponseCallback(
22+
NotificationResponse response) async {
23+
log(response.notificationResponseType.name,
24+
name: "onDidReceiveBackgroundNotificationResponse");
25+
log(response.payload ?? "Empty Payload",
26+
name: "onDidReceiveBackgroundNotificationResponse Payload");
27+
log(response.input ?? "Empty Input",
28+
name: "onDidReceiveBackgroundNotificationResponse Input");
29+
30+
///TODO Handling Background Message Notification
31+
}
32+
33+
class NotificationHandler {
34+
static final FlutterLocalNotificationsPlugin
35+
_flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
36+
static final FirebaseMessaging _messaging = FirebaseMessaging.instance;
37+
38+
static Future<void> initialize() async {
39+
try {
40+
await Firebase.initializeApp(
41+
// options: DefaultFirebaseOptions.currentPlatform,
42+
);
43+
await _firebaseInit();
44+
if (Platform.isIOS) {
45+
await _flutterLocalNotificationsPlugin
46+
.resolvePlatformSpecificImplementation<
47+
IOSFlutterLocalNotificationsPlugin>()
48+
?.requestPermissions(
49+
alert: true,
50+
badge: true,
51+
sound: true,
52+
);
53+
} else {
54+
await _flutterLocalNotificationsPlugin
55+
.resolvePlatformSpecificImplementation<
56+
AndroidFlutterLocalNotificationsPlugin>()
57+
?.requestNotificationsPermission();
58+
}
59+
const androidInitializationSettings =
60+
AndroidInitializationSettings("@mipmap/ic_launcher");
61+
const darwinInitializationSettings = DarwinInitializationSettings(
62+
requestProvisionalPermission: true, requestCriticalPermission: true);
63+
InitializationSettings settings = const InitializationSettings(
64+
android: androidInitializationSettings,
65+
iOS: darwinInitializationSettings,
66+
);
67+
await _flutterLocalNotificationsPlugin.initialize(
68+
settings,
69+
onDidReceiveBackgroundNotificationResponse:
70+
didReceiveBackgroundNotificationResponseCallback,
71+
onDidReceiveNotificationResponse: (response) {
72+
//ToDo
73+
///Handle notification responses;
74+
log(response.notificationResponseType.name,
75+
name: "onDidReceiveNotificationResponse");
76+
log(response.payload ?? "Empty Payload",
77+
name: "onDidReceiveNotificationResponse Payload");
78+
log(response.input ?? "Empty Input",
79+
name: "onDidReceiveNotificationResponse Input");
80+
},
81+
);
82+
} catch (_) {}
83+
}
84+
85+
static Future<void> _firebaseInit() async {
86+
try {
87+
NotificationSettings notificationSettings =
88+
await _messaging.requestPermission();
89+
log(notificationSettings.authorizationStatus.name,
90+
name: "Notification Permission");
91+
92+
///Whenever User Click On Background Notification App Is Terminated....Handle On Tap Through This Method!!
93+
_messaging.getInitialMessage().then((remoteMessage) {
94+
if (remoteMessage != null) {
95+
log("Notification Click Event On Background Application. Data ${remoteMessage.data}, Title ${remoteMessage.notification?.title}");
96+
Future.delayed(const Duration(seconds: 2), () {
97+
if (navigatorKey.currentContext != null) {
98+
///ToDo Notification Handle On background notification click;
99+
}
100+
});
101+
102+
///ToDo Notification Handle On Click;
103+
}
104+
});
105+
106+
///Whenever Notification Coming And App Is Not Terminated And Open In Background Only For Show Notification..!!
107+
FirebaseMessaging.onMessage.listen((remoteMessage) {
108+
log("On Message Notification Data ${remoteMessage.notification.toString()}, Title ${remoteMessage.notification?.title}");
109+
try {
110+
showLocalNotification(remoteMessage);
111+
} catch (_) {
112+
log("Error Catch $_");
113+
}
114+
115+
///ToDo Notification Show On Coming From Firebase;
116+
});
117+
118+
///Whenever User Click On Background Notification App Is Not Terminated Working In Background....Handle On Tap Through This Method!!
119+
FirebaseMessaging.onMessageOpenedApp.listen((remoteMessage) {
120+
log("Background App Notification Data ${remoteMessage.data}, Title ${remoteMessage.notification?.title}");
121+
122+
///ToDo Notification Handle On Click;
123+
});
124+
FirebaseMessaging.onBackgroundMessage(firebaseMessagingBackgroundHandler);
125+
} catch (_) {}
126+
}
127+
128+
static Future<String> getToken() async {
129+
try {
130+
// if (Platform.isIOS) {
131+
// String? apn = await _messaging.getAPNSToken();
132+
// }
133+
return await _messaging.getToken() ?? "";
134+
} catch (_, st) {
135+
log('Stack Trace $st');
136+
return "";
137+
}
138+
}
139+
140+
static Future<void> showLocalNotification(RemoteMessage remoteMessage) async {
141+
log("Check Data ${remoteMessage.toMap()}");
142+
AndroidNotificationDetails androidNotificationDetails =
143+
AndroidNotificationDetails(
144+
remoteMessage.messageId ?? "notification",
145+
"Friend Notification",
146+
color: Colors.transparent,
147+
importance: Importance.max,
148+
priority: Priority.high,
149+
channelShowBadge: true,
150+
// largeIcon: const DrawableResourceAndroidBitmap('@mipmap/ic_launcher'),
151+
);
152+
DarwinNotificationDetails darwinNotificationDetails =
153+
const DarwinNotificationDetails(
154+
presentBanner: true,
155+
presentAlert: true,
156+
presentBadge: true,
157+
presentSound: true,
158+
);
159+
NotificationDetails notificationDetails = NotificationDetails(
160+
android: androidNotificationDetails,
161+
iOS: darwinNotificationDetails,
162+
);
163+
String title =
164+
remoteMessage.notification?.title ?? remoteMessage.data["title"];
165+
String body =
166+
remoteMessage.notification?.body ?? remoteMessage.data["body"] ?? "";
167+
log("remoteMessage showLocalNotification ${remoteMessage.toString()}, Title $title Body $body");
168+
await _flutterLocalNotificationsPlugin.show(
169+
remoteMessage.ttl ?? 0,
170+
title,
171+
body,
172+
notificationDetails,
173+
payload: jsonEncode(
174+
remoteMessage.toMap(),
175+
),
176+
);
177+
}
178+
179+
static Future<void> clearNotification([int? id]) async {
180+
try {
181+
if (id != null) {
182+
await _flutterLocalNotificationsPlugin.cancel(id);
183+
} else {
184+
await _flutterLocalNotificationsPlugin.cancelAll();
185+
}
186+
} catch (_) {}
187+
}
188+
}

lib/firebase_options.dart

Lines changed: 0 additions & 74 deletions
This file was deleted.

lib/main.dart

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import 'package:easy_localization/easy_localization.dart';
33
import 'package:flutter/material.dart';
44
import 'package:flutter/services.dart';
55
import 'package:mvc_flutter/data/local/local_storage.dart';
6+
import 'package:mvc_flutter/data/notification/notification_handler.dart';
67
import 'package:mvc_flutter/data/utils/connectivity_status.dart';
78
import 'package:mvc_flutter/my_app/my_app.dart';
89
import 'package:mvc_flutter/ui/themes/theme.dart';
@@ -11,6 +12,7 @@ import 'package:provider/provider.dart';
1112
void main() async {
1213
WidgetsFlutterBinding.ensureInitialized();
1314
NetworkConnection.networkStreaming();
15+
await NotificationHandler.initialize();
1416
await Prefs.init();
1517
FlutterError.onError = ((error) {
1618
log("Error Stack ${error.stack}");

pubspec.lock

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,14 @@ packages:
99
url: "https://pub.dev"
1010
source: hosted
1111
version: "67.0.0"
12+
_flutterfire_internals:
13+
dependency: transitive
14+
description:
15+
name: _flutterfire_internals
16+
sha256: "554f148e71e9e016d9c04d4af6b103ca3f74a1ceed7d7307b70a0f41e991eb77"
17+
url: "https://pub.dev"
18+
source: hosted
19+
version: "1.3.26"
1220
analyzer:
1321
dependency: transitive
1422
description:
@@ -305,6 +313,30 @@ packages:
305313
url: "https://pub.dev"
306314
source: hosted
307315
version: "2.12.0"
316+
firebase_messaging:
317+
dependency: "direct main"
318+
description:
319+
name: firebase_messaging
320+
sha256: "34fac43b70d5c41dc864eeb52417128da1f68b0a48604a0c56cd3190f0f609b8"
321+
url: "https://pub.dev"
322+
source: hosted
323+
version: "14.7.20"
324+
firebase_messaging_platform_interface:
325+
dependency: transitive
326+
description:
327+
name: firebase_messaging_platform_interface
328+
sha256: "1dcf7d0d6776396bb2e488c53b0e4cc671c45a65717a73d881e52190d23aca3c"
329+
url: "https://pub.dev"
330+
source: hosted
331+
version: "4.5.28"
332+
firebase_messaging_web:
333+
dependency: transitive
334+
description:
335+
name: firebase_messaging_web
336+
sha256: ceabccf24d15d03c89dfd6c7eaef11c58fbf00b9c76ebc94028408943b8d2bfd
337+
url: "https://pub.dev"
338+
source: hosted
339+
version: "3.7.0"
308340
fixnum:
309341
dependency: transitive
310342
description:
@@ -334,6 +366,30 @@ packages:
334366
url: "https://pub.dev"
335367
source: hosted
336368
version: "3.0.1"
369+
flutter_local_notifications:
370+
dependency: "direct main"
371+
description:
372+
name: flutter_local_notifications
373+
sha256: f9a05409385b77b06c18f200a41c7c2711ebf7415669350bb0f8474c07bd40d1
374+
url: "https://pub.dev"
375+
source: hosted
376+
version: "17.0.0"
377+
flutter_local_notifications_linux:
378+
dependency: transitive
379+
description:
380+
name: flutter_local_notifications_linux
381+
sha256: "33f741ef47b5f63cc7f78fe75eeeac7e19f171ff3c3df054d84c1e38bedb6a03"
382+
url: "https://pub.dev"
383+
source: hosted
384+
version: "4.0.0+1"
385+
flutter_local_notifications_platform_interface:
386+
dependency: transitive
387+
description:
388+
name: flutter_local_notifications_platform_interface
389+
sha256: "7cf643d6d5022f3baed0be777b0662cce5919c0a7b86e700299f22dc4ae660ef"
390+
url: "https://pub.dev"
391+
source: hosted
392+
version: "7.0.0+1"
337393
flutter_localizations:
338394
dependency: transitive
339395
description: flutter
@@ -850,6 +906,14 @@ packages:
850906
url: "https://pub.dev"
851907
source: hosted
852908
version: "0.6.1"
909+
timezone:
910+
dependency: transitive
911+
description:
912+
name: timezone
913+
sha256: "1cfd8ddc2d1cfd836bc93e67b9be88c3adaeca6f40a00ca999104c30693cdca0"
914+
url: "https://pub.dev"
915+
source: hosted
916+
version: "0.9.2"
853917
timing:
854918
dependency: transitive
855919
description:

pubspec.yaml

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ dependencies:
1717
cached_network_image: ^3.3.1
1818
easy_localization: ^3.0.5
1919
email_validator: ^2.1.17
20+
flutter_local_notifications: ^17.0.0
2021
flutter_screenutil: ^5.9.0
2122
http_interceptor: ^1.0.2
2223
http: ^0.13.3
@@ -25,8 +26,9 @@ dependencies:
2526
shimmer: ^3.0.0
2627
tuple: ^2.0.2
2728

28-
#Firebase Projects
29-
firebase_core:
29+
#Firebase Pub
30+
firebase_core: ^2.27.1
31+
firebase_messaging: ^14.7.20
3032

3133
dev_dependencies:
3234
flutter_test:

0 commit comments

Comments
 (0)