How to Add Local and Push Notifications in Flutter
2 min readJun 27, 2024
Add permissions Mannfiest File:
<!-- notification-->
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.USE_FULL_SCREEN_INTENT" />
<uses-permission android:name="android.permission.USE_EXACT_ALARM" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
Add dependencies:
flutter_local_notifications: ^17.0.0
firebase_core: ^2.24.2
firebase_messaging: ^14.7.15
Firebase helper File for Push Notification
final FirebaseMessaging _firebaseMessaging = FirebaseMessaging.instance;
Future<void> configureFirebaseMessaging() async {
final settings = await _firebaseMessaging.requestPermission(
alert: true,
announcement: false,
badge: true,
carPlay: false,
criticalAlert: false,
provisional: false,
sound: true,
);
if (kDebugMode) {
print('Permission granted: ${settings.authorizationStatus}');
}
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
NotificationHeplers.showNotification(message);
// // Handle incoming messages when the app is in the foreground.
// notification()
// .showNotification(title: '${message.notification?.title}', body: '${message.notification?.body}');
print("Message received: ${message.notification?.title}");
handleMessage(message);
NotificationHeplers.showNotification(message);
// You can show a local notification here if needed.
});
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
// Handle opening the app from a background state.
// notification()
// .showNotification(title: '${message.notification?.title}', body: '${message.notification?.body}');
print("Message opened app: ${message.notification?.title}");
});
FirebaseMessaging.onBackgroundMessage(_handleBackgroundMessage);
_firebaseMessaging.getToken().then((token) {
print("FCM Token: $token");
GlobalVariable.fcmToken.value = token!;
// localStore().saveStringToPrefs("tokemFCN", token.toString());
// Send the token to your server if needed.
});
}
Future<void> _handleBackgroundMessage(RemoteMessage message) async {
// Handle background messages here.
// notification()
// .showNotification(title: '${message.notification?.title}', body: '${message.notification?.body}');
print("Handling background message: ${message.notification?.title}");
}
void handleMessage(RemoteMessage message) {
print("Local Storage FCM MODEL ${message.data}");
String data = message.data['map'].toString();
// GetStorage().write("fcmModel", data);
}
}
Add Notification Helper File:
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
class NotificationHeplers {
static final FlutterLocalNotificationsPlugin notificationsPlugin =
FlutterLocalNotificationsPlugin();
Future<void> initNotification() async {
AndroidInitializationSettings initializationSettingsAndroid =
const AndroidInitializationSettings('@mipmap/ic_launcher');
//payload
var initializationSettingsIOS = DarwinInitializationSettings(
requestAlertPermission: true,
requestBadgePermission: true,
requestSoundPermission: true,
onDidReceiveLocalNotification:
(int id, String? title, String? body, String? payload) async {});
var initializationSettings = InitializationSettings(
android: initializationSettingsAndroid, iOS: initializationSettingsIOS);
await notificationsPlugin.initialize(initializationSettings,
onDidReceiveNotificationResponse:
(NotificationResponse notificationResponse) async {});
}
// function to show visible notification when app is active
static Future<void> showNotification(RemoteMessage message) async {
AndroidNotificationChannel channel = AndroidNotificationChannel(
message.notification!.android!.channelId.toString(),
message.notification!.android!.channelId.toString(),
importance: Importance.max,
showBadge: true,
playSound: true,
// sound: const RawResourceAndroidNotificationSound('jetsons_doorbell')
);
AndroidNotificationDetails androidNotificationDetails =
AndroidNotificationDetails(
channel.id.toString(), channel.name.toString(),
channelDescription: 'your channel description',
importance: Importance.high,
priority: Priority.high,
playSound: true,
ticker: 'ticker',
// sound: channel.sound
// sound: RawResourceAndroidNotificationSound('jetsons_doorbell')
// icon: largeIconPath
);
const DarwinNotificationDetails darwinNotificationDetails =
DarwinNotificationDetails(
presentAlert: true, presentBadge: true, presentSound: true);
NotificationDetails notificationDetails = NotificationDetails(
android: androidNotificationDetails, iOS: darwinNotificationDetails);
Future.delayed(Duration.zero, () {
notificationsPlugin.show(
0,
message.notification!.title.toString(),
message.notification!.body.toString(),
notificationDetails,
);
});
}
}
Main file initialize:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
configureFirebaseMessaging();
NotificationHeplers().initNotification();
runApp(
const MyApp(),
);
}
Important Note:
first of all Integrate Firebase