Flutter — Firebase push notification complete reference

Santhosh Adiga U
5 min readApr 2, 2023

--

Introduction to Firebase Push Notifications

Firebase Cloud Messaging (FCM) is a cloud-based messaging solution that enables app developers to send notifications and messages to mobile devices, web applications, and desktop applications. Firebase Push Notifications is a feature of FCM that allows developers to send notifications to their users in real-time.

Firebase Push Notifications are an essential tool for any app that needs to keep its users updated with the latest information or alerts. It can be used to notify users about new updates, messages, orders, or anything else that requires their attention.

Setting up Firebase Console

Before we begin, we need to set up Firebase Console for our Flutter project. Follow the steps below to set up Firebase Console:

  1. Go to the Firebase Console and sign in with your Google account.
  2. Click on the “Create Project” button.
  3. Enter a name for your project and select your country/region. Then click on the “Create Project” button.
  4. Once your project is created, click on the “Add app” button to add your Flutter app to the project.
  5. Enter your app’s name and package name. Then click on the “Register App” button.

Adding Firebase to Flutter project

Now that we have set up Firebase Console, we need to add Firebase to our Flutter project. Follow the steps below to add Firebase to your Flutter project:

Open your Flutter project in Android Studio or Visual Studio Code.

Open the pubspec.yaml file and add the following dependencies:

dependencies:
firebase_core: ^1.10.0
firebase_messaging: ^11.2.2

Run the command flutter pub get in the terminal to download and install the dependencies.

Implementing Firebase Messaging in Flutter

Now that we have added Firebase to our Flutter project, we can start implementing Firebase Messaging in Flutter. Follow the steps below to implement Firebase Messaging in your Flutter project:

Open the main.dart file and add the following code to initialize Firebase:

import 'package:firebase_core/firebase_core.dart';

void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}

Create a new file called messaging_service.dart. This file will contain the code to handle incoming messages.

import 'package:firebase_messaging/firebase_messaging.dart';

class MessagingService {
final FirebaseMessaging _fcm = FirebaseMessaging.instance;

Future<void> init() async {
_fcm.requestPermission();

FirebaseMessaging.onMessage.listen((RemoteMessage message) {
print("onMessage: $message");
});

FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
print("onMessageOpenedApp: $message");
});
}
}

In the init() method, we request permission to receive notifications from the user. Then, we listen to incoming messages using the onMessage and onMessageOpenedApp callbacks. The onMessage callback is called when the app is in the foreground, and the onMessageOpenedApp callback is called when the user taps on a notification.

Initialize the MessagingService in the initState() method of the main widget. Here’s how :

class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
final messagingService = MessagingService();

@override
void initState() {
super.initState();
messagingService.init();
}

@override
Widget build(BuildContext context) {
// ...
}
}

Finally, add the following lines of code to the AndroidManifest.xml file located in the android/app/src/main directory of your Flutter project. This file is used to configure your app for Android devices.

<manifest ...>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.VIBRATE" />

<application ...>
<service android:name=".MessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
</application>
</manifest>

This code adds the necessary permissions for your app to receive push notifications on Android devices.

Sending Firebase Push Notifications

Now that we have implemented Firebase Messaging in our Flutter project, we can send push notifications to our users. Follow the steps below to send push notifications using Firebase Console:

  1. Go to your Firebase Console and select your project.
  2. Click on the “Cloud Messaging” tab from the left sidebar.
  3. Click on the “New Notification” button to create a new notification.
  4. Enter the notification title and body.
  5. Under “Target”, select “User Segment”.
  6. Click on the “Add condition” button and select “App Version”.
  7. Set the app version to “All app versions” and click on the “Add” button.
  8. Click on the “Send Test Message” button to send a test notification to your device.

Receiving Firebase Push Notifications

Now that we have sent a push notification, let’s see how we can receive it in our Flutter app. When the app is in the foreground, the onMessage callback in messaging_service.dart will be called. When the user taps on a notification, the onMessageOpenedApp callback will be called.

To test this, run your Flutter app and send a push notification using Firebase Console. If everything is set up correctly, you should see the notification in the console log.

Handling the click of a push notification:

Handling the click of a push notification is an important aspect of implementing Firebase Push Notifications in Flutter. When the user taps on a notification, you may want to open a specific screen or perform a certain action within your app. In this section, we will cover how to handle the click of a push notification and efficiently route the user to the desired screen.

When the user taps on a notification, the onMessageOpenedApp callback in messaging_service.dart will be called. This callback provides a RemoteMessage object that contains the notification data.

To handle the click of a push notification, we can extract the necessary data from the RemoteMessage object and perform the desired action. Here's an example:

void _handleNotificationClick(RemoteMessage message) {
// Extract data from the message
final notificationData = message.data;

// Perform the desired action
if (notificationData.containsKey('screen')) {
final screen = notificationData['screen'];
Navigator.of(context).pushNamed(screen);
} else {
// Handle other types of notifications
}
}

In this example, we extract the screen key from the notification data and use the Navigator class to navigate to the desired screen.

Efficiently routing the user to the desired screen:

Routing the user to the desired screen efficiently is important to provide a smooth and seamless user experience. One way to do this is to use named routes in your Flutter app.

Named routes allow you to define a mapping between a route name and a widget. This way, you can easily navigate to a specific screen by using its name. Here’s an example:

MaterialApp(
// Define named routes
routes: {
'/home': (context) => HomePage(),
'/profile': (context) => ProfilePage(),
'/settings': (context) => SettingsPage(),
},
);

In this example, we define three named routes: /home, /profile, and /settings. Now, we can use these routes to navigate to the desired screen.

void _handleNotificationClick(RemoteMessage message) {
// Extract data from the message
final notificationData = message.data;

// Perform the desired action
if (notificationData.containsKey('screen')) {
final screen = notificationData['screen'];
Navigator.of(context).pushNamed(screen);
} else {
// Handle other types of notifications
}
}

In this example, we use the pushNamed method of the Navigator class to navigate to the desired screen.

By using named routes, you can efficiently route the user to the desired screen and provide a smooth and seamless user experience.

Handling the click of a push notification and efficiently routing the user to the desired screen are important aspects of implementing Firebase Push Notifications in Flutter. By using the onMessageOpenedApp callback and named routes, you can provide a seamless and efficient user experience for your app users.

Conclusion

In this article, we learned how to implement Firebase Push Notifications in Flutter. We set up Firebase Console, added Firebase to our Flutter project, implemented Firebase Messaging in Flutter, and sent and received push notifications and also handled routing on-click of push notification. Firebase Push Notifications are a powerful tool that can help you keep your users engaged with your app.

--

--

Santhosh Adiga U
Santhosh Adiga U

Written by Santhosh Adiga U

Founder of Anakramy ., dedicated to creating innovative AI-driven cybersecurity solutions.

Responses (3)