Flutter Firebase push notifications


Firbase:

  1. 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

  2. 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
  3. Write background handler

 Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
	  await Firebase.initializeApp();
	  print('Handling a background message ${message.messageId}');
	}
 
  1. Register above handler to firebase instance
    FirebaseMessaging.onBackgroundMessage(firebaseMessagesBackgroundHandler);

  2. 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,
    );
 
  1. Create flutter local notification plugin for notification alert
    FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();

  2. register android channel with flutter local notification plugin object

 	await flutterLocalNotificationsPlugin
        .resolvePlatformSpecificImplementation<
            AndroidFlutterLocalNotificationsPlugin>()
        ?.createNotificationChannel(channel);
 
  1. Write foreground handler
 Future<void> firebaseMessagesForeGroundHandler(RemoteMessage message) async {

	} 
  1. register foreground handler to FCM
 	FirebaseMessaging.onMessage.listen((RemoteMessage message) {
      firebaseMessagesForeGroundHandler(message);
    });
 
  1. Init android, ios settings
 AndroidInitializationSettings initializationSettingsAndroid = AndroidInitializationSettings('ic_notifications');
		IOSInitializationSettings initializationSettingsIOS = IOSInitializationSettings( requestSoundPermission: false, requestBadgePermission: false, requestAlertPermission: false);
 
  1. Add above settings to flutterLocalNotificationsPlugin
 final InitializationSettings initializationSettings = InitializationSettings(
	    android: initializationSettingsAndroid,
	    iOS: initializationSettingsIOS,
	  );
	  flutterLocalNotificationsPlugin.initialize(
	    initializationSettings,
	    onSelectNotification: onSelectNotification,
	  ); 
  1. Show notification
 flutterLocalNotificationsPlugin.show(
        notification.hashCode,
        notification.title,
        notification.body,
        NotificationDetails(
          android: AndroidNotificationDetails(
            channel.id,
            channel.name,
            channel.description,
            icon: 'launch_background',
          ),
        ));