Continuation: Enhancing Push Notifications in Flutter Using Firebase

Push Notification with FCM & Flutter Android & IOS

Enhancing Push Notifications in Flutter 

In the previous blog post, we covered the fundamental steps to integrate push notifications into a Flutter app using Firebase Cloud Messaging (FCM). In this continuation, we'll explore how to open a specific page when the user clicks on a notification, thereby enhancing the user experience and providing contextual information.

Let's dive into the code changes required to handle notifications effectively:

Updating firebase_api.dart
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:pushnotification/Page/notification_screen.dart';
import 'package:pushnotification/main.dart';

class FirebaseApi {
  final _firebaseMessaging = FirebaseMessaging.instance;

  void handleMessage(RemoteMessage? message) {
    if (message == null) return;
    navigatorKey.currentState?.pushNamed(NotificationScreen.route, arguments: message);
  }

  Future<void> handleBackgroundMessage(RemoteMessage message) async {
    if (message == null) return;
    navigatorKey.currentState?.pushNamed(NotificationScreen.route, arguments: message);
  }

  Future<void> initPushNotification() async {
    await FirebaseMessaging.instance.setForegroundNotificationPresentationOptions(
      alert: true,
      badge: true,
      sound: true,
    );
    FirebaseMessaging.instance.getInitialMessage().then(handleMessage);
    FirebaseMessaging.onMessageOpenedApp.listen(handleMessage);
    FirebaseMessaging.onBackgroundMessage(handleBackgroundMessage);
  }

  Future<void> initNotifications() async {
    await _firebaseMessaging.requestPermission();
    final fCMToken = await _firebaseMessaging.getToken();
    print('Token:  $fCMToken');
    initPushNotification();
  }
}

Explanation:

  • We've added a handleMessage method to handle notifications when the app is in the foreground or when it's opened from a terminated state.
  • The handleBackgroundMessage method is responsible for handling notifications received when the app is in the background.
  • Both methods utilize the navigatorKey to navigate to the NotificationScreen when a notification is tapped.
  • The initPushNotification function initializes push notifications and sets up listeners for various notification events.
Creating Notification Screen

We need to create a new screen to display notification details. Let's create two files home_screen.dart and notification_screen.dart in the Page folder:

home_screen.dart
import 'package:flutter/material.dart';

class HomeScreen extends StatelessWidget {
  const HomeScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) => Scaffold(
    appBar: AppBar(title: const Text('Push Notification'),),
    body: const Center(child: Text('Home Page'),),
  );
}

notification_screen.dart
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';

class NotificationScreen extends StatelessWidget {
  const NotificationScreen({Key? key}) : super(key: key);
  static const route = '/notification-screen';

  @override
  Widget build(BuildContext context) {
    final message = ModalRoute.of(context)!.settings.arguments as RemoteMessage?;
    return Scaffold(
      appBar: AppBar(title: Text('Notification Screen'),),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('Title: ${message?.notification?.title ?? "No Title"}'),
            SizedBox(height: 20),
            Text('Body: ${message?.notification?.body ?? "No Body"}'),
          ],
        ),
      ),
    );
  }
}

Explanation:

  • We've created a NotificationScreen widget to display the title and body of the received notification.
  • The route constant is used to define the route for navigation.
Updating main.dart

Lastly, let's update the main.dart file to incorporate the new screen and set up the app's navigation:
import 'dart:io';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:pushnotification/Page/home_screen.dart';
import 'package:pushnotification/Page/notification_screen.dart';
import 'package:pushnotification/api/firebase_api.dart';

final navigatorKey = GlobalKey<NavigatorState>();

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  Platform.isAndroid
      ? await Firebase.initializeApp(
    options: const FirebaseOptions(
      apiKey: 'YOUR_API_KEY',
      appId: 'YOUR_APP_ID',
      messagingSenderId: 'YOUR_SENDER_ID',
      projectId: 'YOUR_PROJECT_ID',
    ),
  )
      : await Firebase.initializeApp();

  await FirebaseApi().initNotifications();
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      navigatorKey: navigatorKey,
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const HomeScreen(),
      routes: {
        NotificationScreen.route: (context) => NotificationScreen(),
      },
    );
  }
}

Explanation:

We've updated the main.dart file to include the NotificationScreen route.
The navigatorKey is used to enable navigation to the notification screen when a notification is tapped.
With these updates, your Flutter app is now equipped to open a specific page when the user clicks on a notification, providing a seamless and intuitive user experience. Push notifications, coupled with deep linking to relevant screens, can significantly enhance user engagement and retention.

In conclusion, the implementation of push notifications in a Flutter application has been further enhanced by enabling the app to open a specific page when a user interacts with a notification. In this continuation of our tutorial series, we've delved deeper into the codebase to incorporate the necessary logic and screens to achieve this functionality seamlessly.

Comments

Popular posts from this blog

Push Notifications in .NET MAUI: A Comprehensive Guide

Explore the UI libraries available for .NET MAUI at no cost.

Push Notification using Firebase in xamarin form (Android and IOS)