Flutter Firebase push notifications
Firbase:
-
Add firebase dependencies in flutter project pubspec.yaml file
firebase_core: ^1.2.0
firebase_messaging: ^10.0.0
flutter_local_notifications: ^5.0.0+4 -
Get FCM token that is unique for device and app
String token = await FirebaseMessaging.instance.getToken();- Store token in shared pref, to easy access from anywhere
-
Write background handler
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
await Firebase.initializeApp();
print('Handling a background message ${message.messageId}');
}
-
Register above handler to firebase instance
FirebaseMessaging.onBackgroundMessage(firebaseMessagesBackgroundHandler); -
Create a android channel for android 8+
AndroidNotificationChannel channel = AndroidNotificationChannel(
'high_importance_channel', // id
'High Importance Notifications', // title
'This channel is used for important notifications.', // description
importance: Importance.high,
);
-
Create flutter local notification plugin for notification alert
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin(); -
register android channel with flutter local notification plugin object
await flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin>()
?.createNotificationChannel(channel);
- Write foreground handler
Future<void> firebaseMessagesForeGroundHandler(RemoteMessage message) async {
}
- register foreground handler to FCM
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
firebaseMessagesForeGroundHandler(message);
});
- Init android, ios settings
AndroidInitializationSettings initializationSettingsAndroid = AndroidInitializationSettings('ic_notifications');
IOSInitializationSettings initializationSettingsIOS = IOSInitializationSettings( requestSoundPermission: false, requestBadgePermission: false, requestAlertPermission: false);
- Add above settings to flutterLocalNotificationsPlugin
final InitializationSettings initializationSettings = InitializationSettings(
android: initializationSettingsAndroid,
iOS: initializationSettingsIOS,
);
flutterLocalNotificationsPlugin.initialize(
initializationSettings,
onSelectNotification: onSelectNotification,
);
- Show notification
flutterLocalNotificationsPlugin.show(
notification.hashCode,
notification.title,
notification.body,
NotificationDetails(
android: AndroidNotificationDetails(
channel.id,
channel.name,
channel.description,
icon: 'launch_background',
),
));