Flutter using Firebase Cloud Messaging

Step-by-Step Guide: Setting up Push Notifications in Flutter using Firebase Cloud Messaging

In today’s world, mobile applications have become an integral part of our daily lives. These applications have made our lives easier and more comfortable. Push notifications have emerged as a crucial feature in mobile applications that keep users updated and engaged. Flutter, Google’s mobile app development framework, is an excellent platform for developing cross-platform mobile applications. In this blog, we will discuss setting up push notifications using Firebase Cloud Messaging (FCM) in Flutter applications.

Firebase Cloud Messaging is a free service provided by Google that allows developers to send push notifications to Android, iOS, and web applications. It is a powerful tool that allows developers to engage their users and improve their application’s retention rates. FCM provides a simple and easy-to-use API that developers can use to send notifications to their users. Firebase also provides an easy integration with Flutter applications.

Now let’s start setting up the push notifications using Firebase Cloud Messaging in Flutter applications.

Step 1: Create a Firebase project To use Firebase services, you need to create a Firebase project. Go to the Firebase Console and create a new project. Follow the instructions provided by Firebase to create a new project.

Step 2: Add Firebase to your Flutter project After creating a Firebase project, you need to add the Firebase SDK to your Flutter project. To add Firebase to your Flutter project, you need to follow these steps:

Go to the Firebase Console and click on the “Add Firebase to your Android/iOS app” button.

Provide the required information, such as your package name and app nickname, to generate the configuration files.

Download the configuration files and add them to your Flutter project.

Step 3: Add the Firebase Cloud Messaging dependency After adding Firebase to your Flutter project, you need to add the Firebase Cloud Messaging dependency to your project. To add the Firebase Cloud Messaging dependency, add the following line to your project’s pubspec.yaml file:

firebase_messaging: ^11.2.0

Step 4: Configure Firebase Cloud Messaging After adding the Firebase Cloud Messaging dependency, you need to configure Firebase Cloud Messaging in your Flutter project. To configure Firebase Cloud Messaging, you need to follow these steps:

1.Add the following code to your main.dart file to initialize Firebase:

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

2.Create a new class named ‘PushNotificationService’ and add the following code:

class PushNotificationService {
FirebaseMessaging _fcm = FirebaseMessaging.instance;

Future initialize() async {
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
print(‘Got a message whilst in the foreground!’);
print(‘Message data: ${message.data});

if (message.notification != null) {
print(‘Message also contained a notification: ${message.notification});
}
});
}

Future<String?> getToken() async {
String? token = await _fcm.getToken();
print(‘Token: $token);
return token;
}
}

This code initializes Firebase Cloud Messaging and provides two functions to get the token and listen to incoming notifications.

Step 5: Test the push notifications After configuring Firebase Cloud Messaging, you can test the push notifications in your Flutter application. To test the push notifications, follow these steps:

1. Start your Flutter application and get the token by calling the getToken() function.

2. Go to the Firebase Console and select your project.

3. Click on the “Cloud Messaging” tab and click on the “New Notification” button.

4. Provide the required information, such as the title and body of the notification, and click on the “Send Test Message” button.

Step 6: Handle notifications in the background or killed mode When the application is in the background or killed mode, the push notifications are handled differently than when the application is in the foreground. In this step, we will handle the notifications when the application is in the background or killed mode.

Add the following code to the PushNotificationService class to listen to incoming notifications when the application is in the background or killed mode:

Future<void> backgroundHandler(RemoteMessage message) async {

print(‘Handling a background message ${message.messageId});}

2. Modify the initialize function in the PushNotificationService class to include the backgroundHandler function:

Future initialize() async {
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
print(‘Got a message whilst in the foreground!’);
print(‘Message data: ${message.data});

if (message.notification != null) {
print(‘Message also contained a notification: ${message.notification});
}
});

FirebaseMessaging.onBackgroundMessage(backgroundHandler);

// Get the token
await getToken();
}

3. Add the following code to the AndroidManifest.xml file to enable the background handling of notifications:

<service
android:name=“com.example.myapp.PushNotificationService”
android:exported=“false”>

<intent-filter>
<action android:name=“com.google.firebase.MESSAGING_EVENT” />
</intent-filter>
</service>

4. To handle the notifications when the application is in the background or killed mode, add the following code to the onLaunch and onResume functions of the MaterialApp widget:

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

class MyApp extends StatelessWidget {
final PushNotificationService _notificationService = PushNotificationService();
@override
Widget build(BuildContext context) {
_notificationService.initialize();

return MaterialApp(
title: ‘My App’,
home: MyHomePage(),
onGenerateRoute: Router.generateRoute,
initialRoute: ‘/’,
onLaunch: (Map<String, dynamic> message) async {
print(‘onLaunch: $message);
// Handle the notification
},
onResume: (Map<String, dynamic> message) async {
print(‘onResume: $message);
// Handle the notification
},
);
}
}

Congratulations! You have now successfully set up push notifications in your Flutter application using Firebase Cloud Messaging, even when the application is in the background or killed mode. Your application can now receive push notifications and handle them appropriately.

Leave a Reply

Your email address will not be published. Required fields are marked *