Flutter Android, Web & iOS Push notifications with Firebase messaging

3 min read 3 hours ago
Published on Sep 27, 2024 This response is partially generated with the help of AI. It may contain inaccuracies.

Table of Contents

Introduction

This tutorial will guide you through the process of implementing push notifications in a Flutter application using Firebase Cloud Messaging (FCM). You will learn how to set up FCM for Android, iOS, and web platforms, handle notifications in the foreground, and manage user interactions with notifications.

Step 1: Configuring Firebase with FlutterFire CLI

  1. Install FlutterFire CLI:

    • Ensure you have Flutter installed on your machine.
    • Run the following command to install the FlutterFire CLI:
      dart pub global activate flutterfire_cli
      
  2. Initialize Firebase:

    • Navigate to your Flutter project directory.
    • Run the command to configure Firebase:
      flutterfire configure
      
    • Follow the prompts to select your Firebase project and platforms.
  3. Add Dependencies:

    • Open your pubspec.yaml file and add the necessary dependencies for Firebase Messaging:
      dependencies:
        firebase_core: latest_version
        firebase_messaging: latest_version
      
  4. Run Flutter Packages Get:

    • Execute the following command to install the added packages:
      flutter pub get
      

Step 2: Setting Up Android Push Notifications

  1. Android Configuration:

    • Open the android/app/build.gradle file.
    • Set the minSdkVersion to at least 21:
      android {
          ...
          defaultConfig {
              ...
              minSdkVersion 21
          }
      }
      
  2. Add Firebase Services:

    • In your android/app/src/main/AndroidManifest.xml, add the necessary permissions and services:
      <manifest>
          <application>
              ...
              <service
                  android:name="com.google.firebase.messaging.FirebaseMessagingService"
                  android:exported="false">
                  <intent-filter>
                      <action android:name="com.google.firebase.MESSAGING_EVENT" />
                  </intent-filter>
              </service>
          </application>
      </manifest>
      
  3. Request Permissions:

    • In your Dart code, request permission to send notifications:
      FirebaseMessaging messaging = FirebaseMessaging.instance;
      
      Future<void> requestNotificationPermissions() async {
          NotificationSettings settings = await messaging.requestPermission();
          if (settings.authorizationStatus == AuthorizationStatus.authorized) {
              print('User granted permission');
          } else {
              print('User declined or has not accepted permission');
          }
      }
      

Step 3: Setting Up iOS Push Notifications

  1. iOS Configuration:

    • Open the ios/Runner/Info.plist file and add the following:
      <key>UIBackgroundModes</key>
      <array>
          <string>fetch</string>
          <string>remote-notification</string>
      </array>
      
  2. Request Permissions:

    • Similar to Android, request permission for notifications in your Dart code.

Step 4: Setting Up Web Push Notifications

  1. Web Configuration:

    • In your index.html, include the Firebase scripts:
      <script src="https://www.gstatic.com/firebasejs/9.0.0/firebase-app.js"></script>
      <script src="https://www.gstatic.com/firebasejs/9.0.0/firebase-messaging.js"></script>
      
  2. Initialize Firebase:

    • In your Dart code, initialize Firebase:
      Firebase.initializeApp().then((_) {
          FirebaseMessaging messaging = FirebaseMessaging.instance;
      });
      
  3. Request Notification Permissions:

    • Ensure to request notification permissions for web users.

Step 5: Handling Notifications in Foreground

  1. Foreground Notifications:
    • Use the following code to handle messages received while the app is in the foreground:
      FirebaseMessaging.onMessage.listen((RemoteMessage message) {
          print('Got a message whilst in the foreground!');
          if (message.notification != null) {
              print('Message also contained a notification: ${message.notification}');
          }
      });
      

Step 6: Handling User Interactions

  1. Notification Interaction:
    • Add a listener for when a user interacts with a notification:
      FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
          print('Message clicked!');
      });
      

Step 7: Implementing Local Notifications

  1. Using flutter_local_notifications:

    • Add the dependency to your pubspec.yaml:
      dependencies:
        flutter_local_notifications: latest_version
      
  2. Set up local notifications:

    • Initialize and configure local notifications in your Dart code. Refer to the flutter_local_notifications package documentation for specifics.

Conclusion

You have now configured push notifications in your Flutter app for Android, iOS, and web using Firebase Messaging. You learned to handle notifications in different states and how to respond to user interactions. Next steps include testing your implementation on actual devices and exploring advanced features like custom notification sounds or rich media notifications. Happy coding!