Skip to content

Instantly share code, notes, and snippets.

@Syed-Waleed-Shah
Created April 25, 2022 09:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Syed-Waleed-Shah/9f55c9b41fdd70555c754aefdecc730d to your computer and use it in GitHub Desktop.
Save Syed-Waleed-Shah/9f55c9b41fdd70555c754aefdecc730d to your computer and use it in GitHub Desktop.
All steps to Integrate FCM notifications in flutter

Integrate FCM notifications in flutter

1) Create a flutter app

Now all setup is done to work with Pushnotification

2) add these 3 Dependencies in pubspec.yaml

firebase_core: ^1.12.0
firebase_messaging: ^11.2.6
flutter_local_notifications: ^9.2.0

3) Setup firebase project at

Firebase : https://console.firebase.google.com/

NOTE : -> After setup firebase project you can receive simple pushnotification from firebase cloud messaging without doing anything additional if you just want to display notifications to users in your app. When user taps on your notification your app will be opened. But if you want to open some specific screen or you want to customize the appearence of your notification then follow along:

4) Add this lines to main() method

main.dart

main() {
    WidgetsFlutterBinding.ensureInitialized();
    await Firebase.initializeApp();
}

5) Now write some code in main.dart to start firebase background services

  1. add this method after import statement in main.dart
	Future<void> backgroundHandler(RemoteMessage message) async {
      	print(message.data.toString());
     	print(message.notification!.title);
	}
  1. call this method from main method after await Firebase.initializeApp();
FirebaseMessaging.onBackgroundMessage(backgroundHandler);

6) Go to the home_screen.dart and start work inside initState() Method

 @override
  void initState() {
    super.initState();

    // 1. This method call when app in terminated state and you get a notification
    // when you click on notification app open from terminated state and you can get notification data in this method

    FirebaseMessaging.instance.getInitialMessage().then(
      (message) {
        print("FirebaseMessaging.instance.getInitialMessage");
        if (message != null) {
          print("New Notification");
          // if (message.data['_id'] != null) {
          //   Navigator.of(context).push(
          //     MaterialPageRoute(
          //       builder: (context) => DemoScreen(
          //         id: message.data['_id'],
          //       ),
          //     ),
          //   );
          // }
        }
      },
    );

    // 2. This method only call when App in forground it mean app must be opened
    FirebaseMessaging.onMessage.listen(
      (message) {
        print("FirebaseMessaging.onMessage.listen");
        if (message.notification != null) {
          print(message.notification!.title);
          print(message.notification!.body);
          print("message.data11 ${message.data}");
          // LocalNotificationService.display(message);

        }
      },
    );

    // 3. This method only call when App in background and not terminated(not closed)
    FirebaseMessaging.onMessageOpenedApp.listen(
      (message) {
        print("FirebaseMessaging.onMessageOpenedApp.listen");
        if (message.notification != null) {
          print(message.notification!.title);
          print(message.notification!.body);
          print("message.data22 ${message.data['_id']}");
        }
      },
    );
  }

7) after all these you send a notification when your app in background then you see some warning in console when you tap on notification like this

Missing Default Notification Channel metadata in AndroidManifest. Default value will be used. Because of this warning you are not getting notification like we get in youtube and other app. To solve this add below line in AndroidManifest.xml: <meta-data android:name="com.google.firebase.messaging.default_notification_channel_id" android:value="pushnotificationapp"/>

8) After donign this you get another warning (this warning will show when you send notification with channel name pushnotificationapp

Notification Channel requested (pushnotificationapp) has not been created by the app. Manifest configuration, or default, value will be used so now we need to create a channel with name pushnotificationapp we do it with the help of flutter local notification

9) Go inside lib -> create folder -> notificationservice -> create file inside notificationservice -> local_notification_service.dart

go inside the local_notification_service.dart and create a class

class LocalNotificationService{
 // inside class create instance of FlutterLocalNotificationsPlugin see below 

static final FlutterLocalNotificationsPlugin _notificationsPlugin =
      FlutterLocalNotificationsPlugin();

// after this create a method initialize to initialize  localnotification 

static void initialize(BuildContext context) {
    // initializationSettings  for Android
    const InitializationSettings initializationSettings =
        InitializationSettings(
      android: AndroidInitializationSettings("@mipmap/ic_launcher"),
    );

    _notificationsPlugin.initialize(
      initializationSettings,
      onSelectNotification: (String? id) async {
        print("onSelectNotification");
        if (id!.isNotEmpty) {
          print("Router Value1234 $id");

          // Navigator.of(context).push(
          //   MaterialPageRoute(
          //     builder: (context) => DemoScreen(
          //       id: id,
          //     ),
          //   ),
          // );

          
        }
      },
    );
  }


// after initialize we create channel in createanddisplaynotification method
static void createanddisplaynotification(RemoteMessage message) async {
    try {
      final id = DateTime.now().millisecondsSinceEpoch ~/ 1000;
      const NotificationDetails notificationDetails = NotificationDetails(
        android: AndroidNotificationDetails(
          "pushnotificationapp",
          "pushnotificationappchannel",
          importance: Importance.max,
          priority: Priority.high,
        ),
      );

      await _notificationsPlugin.show(
        id,
        message.notification!.title,
        message.notification!.body,
        notificationDetails,
        payload: message.data['_id'],
      );
    } on Exception catch (e) {
      print(e);
    }
  }

}

10) Call initialize method from main method

LocalNotificationService.initialize(); and uncomment last line from FirebaseMessaging.onMessage method in homescreen

11) How to send Push Notification Using Postman

[Step 1] Get the device token

Future<void> getDeviceTokenToSendNotification() async {
	final FirebaseMessaging _fcm = FirebaseMessaging.instance;
	final token = await _fcm.getToken();
	deviceTokenToSendPushNotification = token.toString();
	print("Token Value $deviceTokenToSendPushNotification");
}

[Step 2] Go to firebase console -> select your project -> go to project settings -> copy server key

[step 3] open postman

go to Headers section and set Header
Content-Type -> application/json
Authorization ->key=YOUR_SERVER_KEY

[step 4] now you are ready to send notification via postman

1. method post
2. API Url -> https://fcm.googleapis.com/fcm/send
3. json Body ->
{
    "registration_ids": [
        "dJVh8FWXQ_2ipxYVpFaXCT:APA91bFyHc6mSyWHMgN7_iVDk5zB1WwB6qKlZGcxIpRBFnnxl4CRRi9qTCD3oLrJU6OY12AGzuM8_XZkEiWuwXUMc8nIlupjfrjIgNdzuhmq3bAOBYdw1z_8nmcSWyFNin24jkfgFTC5"
    ],
    "notification": {
        "body": "New Video has been uploaded",
        "title": "Inventorcode",
        "android_channel_id": "pushnotificationapp",
        "sound": false
    }
}

[Step 5] If you want to send extra data

add data key in josn like this

{
	"notification"{
			}
	"data":{"_id":1}
}

NOTE-> For single user user "to":"" or for multipal users use "registration_ids": [] array

"registration_ids": [
    "dJVh8FWXQ_2ipxYVpFaXCT:APA91bFyHc6mSyWHMgN7_iVDk5zB1WwB6qKlZGcxIpRBFnnxl4CRRi9qTCD3oLrJU6OY12AGzuM8_XZkEiWuwXUMc8nIlupjfrjIgNdzuhmq3bAOBYdw1z_8nmcSWyFNin24jkfgFTC5"
]

NOTE ->>>>>>>>>>> If you want to send image in notification add "image":"", key in "":{"notification":""},

{
    "registration_ids": [
        "dJVh8FWXQ_2ipxYVpFaXCT:APA91bFyHc6mSyWHMgN7_iVDk5zB1WwB6qKlZGcxIpRBFnnxl4CRRi9qTCD3oLrJU6OY12AGzuM8_XZkEiWuwXUMc8nIlupjfrjIgNdzuhmq3bAOBYdw1z_8nmcSWyFNin24jkfgFTC5"
    ],
    "notification": {
        "body": "New Video has been uploaded",
        "title": "Inventorcode",
        "android_channel_id": "pushnotificationapp",
        "image":"https://cdn2.vectorstock.com/i/1000x1000/23/91/small-size-emoticon-vector-9852391.jpg",
        "sound": false
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment