Flutter | Firebase | Push Notification (FCM)

Mohammed Waseem
3 min readJan 26, 2022

For info on firebase implementation to flutter project visit this page:

To begin, First of all make sure you have the following packages:

  1. firebase_messaging <latest version>
  2. firebase_analytics <latest version>
  3. firebase_core <latest version>

Then, in your main.dart file modify the code to look like below image

Note: Devices receive notifications based on their tokens. It means each device has a unique token and the notification is sent to the specific user/device based on the token given.

Now, I will show you how to get the device token, and you can implement the below code in any dart file, it doesn't have to be in main.dart.

Enter the below code in your stateful widget to initialize your instance

The notification can appear in 3 states

  1. Foreground,
  2. Background
  3. On message opened

The below code shown are to handle the 3 states of the notification and the getToken() function gets the device token. Store the token in database for future use.

Run the application in the device and make sure whichever page the code is written on is also run.

When the getToken() function is run the token will be printed in the debug console so copy it (Ctrl+c).

And that's all for the coding part.

Next, go to the firebase console to the cloud messaging section

Click on SEND YOUR FIRST MESSAGE

Then enter the notification text as you like and click on send test message button.

Paste the token you copied previously

Select the token and click the test button and your notification should be printed in the debug console as we used the print method in the notification states.

And that's how the push-notifications works

--

--