Skip to content

Instantly share code, notes, and snippets.

@YousefMohamed6
Created May 16, 2025 12:49
Show Gist options
  • Save YousefMohamed6/cff5b49068c514926b096afd750eefb0 to your computer and use it in GitHub Desktop.
Save YousefMohamed6/cff5b49068c514926b096afd750eefb0 to your computer and use it in GitHub Desktop.
import 'dart:async';
import 'dart:io';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
@pragma('vm:entry-point')
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
await NotificationService.instance.setupFlutterNotifications();
await NotificationService.instance.showNotification(message);
}
class NotificationService {
NotificationService._();
static final NotificationService instance = NotificationService._();
final _messaging = FirebaseMessaging.instance;
final _localNotifications = FlutterLocalNotificationsPlugin();
bool _isFlutterLocalNotificationsInitialized = false;
Future<void> initialize() async {
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
// Request permission
await _requestPermission();
// Setup message handlers
await _setupMessageHandlers();
// Get FCM token
String token = await getDeviceToken();
print('FCM Token: $token');
}
Future<String> getDeviceToken() async {
late String token;
if (Platform.isIOS) {
token = await _messaging.getAPNSToken() ?? '';
} else {
token = await _messaging.getToken() ?? '';
}
return token;
}
Future<void> _requestPermission() async {
// ignore: unused_local_variable
final settings = await _messaging.requestPermission(
alert: true,
badge: true,
sound: true,
provisional: false,
announcement: false,
carPlay: false,
criticalAlert: false,
);
}
Future<void> setupFlutterNotifications() async {
if (_isFlutterLocalNotificationsInitialized) {
return;
}
// android setup
const channel = AndroidNotificationChannel(
'high_importance_channel',
'High Importance Notifications',
description: 'This channel is used for important notifications.',
importance: Importance.high,
);
await _localNotifications
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin
>()
?.createNotificationChannel(channel);
const initializationSettingsAndroid = AndroidInitializationSettings(
'@mipmap/ic_launcher',
);
// ios setup
// ignore: prefer_const_constructors
final initializationSettingsDarwin = DarwinInitializationSettings();
final initializationSettings = InitializationSettings(
android: initializationSettingsAndroid,
iOS: initializationSettingsDarwin,
);
// flutter notification setup
await _localNotifications.initialize(
initializationSettings,
onDidReceiveNotificationResponse: (details) {},
);
_isFlutterLocalNotificationsInitialized = true;
}
Future<void> showNotification(RemoteMessage message) async {
RemoteNotification? notification = message.notification;
AndroidNotification? android = message.notification?.android;
if (notification != null && android != null) {
await _localNotifications.show(
notification.hashCode,
notification.title,
notification.body,
const NotificationDetails(
android: AndroidNotificationDetails(
'high_importance_channel',
'High Importance Notifications',
channelDescription:
'This channel is used for important notifications.',
importance: Importance.high,
priority: Priority.high,
icon: '@mipmap/ic_launcher',
),
iOS: DarwinNotificationDetails(
presentAlert: true,
presentBadge: true,
presentSound: true,
),
),
payload: message.data.toString(),
);
}
}
Future<void> _setupMessageHandlers() async {
//foreground message
FirebaseMessaging.onMessage.listen((message) {
showNotification(message);
});
// background message
FirebaseMessaging.onMessageOpenedApp.listen(_handleBackgroundMessage);
// opened app
final initialMessage = await _messaging.getInitialMessage();
if (initialMessage != null) {
_handleBackgroundMessage(initialMessage);
}
}
void _handleBackgroundMessage(RemoteMessage message) {
if (message.data['type'] == 'chat') {
// open chat screen
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment