Home > database >  firebase messaging handling with local notification
firebase messaging handling with local notification

Time:09-12

I am new to flutter and I want to work with firebase messaging. I want to send messages with firebase to phones. I read the documents but I'm very confused. what should I do?

CodePudding user response:

This is my firebaseHandling class:

import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:get/get.dart';
import 'package:plasco/getx/user_controller.dart';
import 'package:plasco/model/payload.dart';
import 'package:plasco/service/page_handler.dart';
import 'package:plasco/service/plasco_request.dart';

class FirebaseMassagingHandler {
  FirebaseMassagingHandler._();
  static AndroidNotificationChannel channel = const AndroidNotificationChannel(
    'com.example.plasco', // id
    'plasco', // title
    importance: Importance.high,
  );
  static FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
      FlutterLocalNotificationsPlugin();

  static Future<void> config() async {
    FirebaseMessaging messaging = FirebaseMessaging.instance;
    try {
      UserController _userController = Get.put(UserController());
      RemoteMessage newMessage = const RemoteMessage();
      await messaging.requestPermission(
        sound: true,
        badge: true,
        alert: true,
        announcement: false,
        carPlay: false,
        criticalAlert: false,
        provisional: false,
      );

      RemoteMessage? initialMessage =
          await FirebaseMessaging.instance.getInitialMessage();
      if (initialMessage != null) {
        PayloadModel payloadRes = PayloadModel.fromJson(initialMessage.data);
        firebasePageRouter(page: payloadRes.page!, id: payloadRes.id);
      }

      var initializationSettingsAndroid =
          const AndroidInitializationSettings("ic_launcher");
      var initializationSettings =
          InitializationSettings(android: initializationSettingsAndroid);
      flutterLocalNotificationsPlugin.initialize(
        initializationSettings,
        onSelectNotification: (value) async {
          PayloadModel payloadRes = PayloadModel.fromJson(newMessage.data);
          firebasePageRouter(page: payloadRes.page!, id: payloadRes.id);
        },
      );
      await FirebaseMessaging.instance
          .setForegroundNotificationPresentationOptions(
              alert: true, badge: true, sound: true);

      String? token = await FirebaseMessaging.instance.getToken();
      _userController.token = token;
      FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
        debugPrint("\n notification on onMessageOpenedApp function \n");
        newMessage = message;
        PayloadModel payloadRes = PayloadModel.fromJson(newMessage.data);
        firebasePageRouter(
            page: payloadRes.page!, id: payloadRes.id, goToMain: true);
      });
      FirebaseMessaging.onMessage.listen((RemoteMessage message) async {
        debugPrint("\n notification on onMessage function \n");
        newMessage = message;
        await _showNotification(message: newMessage);
      });
    } on Exception catch (e) {
      debugPrint("$e");
    }
  }

  static Future<void> _showNotification({RemoteMessage? message}) async {
    RemoteNotification? notification = message!.notification;
    AndroidNotification? androidNotification = message.notification!.android;
    AppleNotification? appleNotification = message.notification!.apple;

    if (notification != null &&
        (androidNotification != null || appleNotification != null)) {
      flutterLocalNotificationsPlugin.show(
        notification.hashCode,
        notification.title,
        notification.body,
        NotificationDetails(
          android: AndroidNotificationDetails(
            channel.id,
            channel.name,
            icon: "ic_launcher",
            playSound: true,
            enableVibration: true,
            priority: Priority.high,
            channelShowBadge: true,
            importance: Importance.high,
          ),
          iOS: const IOSNotificationDetails(
            presentAlert: true,
            presentBadge: true,
            presentSound: true,
          ),
        ),
        payload: message.data.toString(),
      );
    }
    PlascoRequests().initReport();
  }

  static Future<void> firebaseMessagingBackground(RemoteMessage message) async {
    await Firebase.initializeApp();
    debugPrint("message data: ${message.data}");
  }
}

And you have to create this function:

      Future firebaseInit() async {
    await Firebase.initializeApp();
    FirebaseMessaging.onBackgroundMessage(
      FirebaseMassagingHandler.firebaseMessagingBackground,
    );
    if (!kIsWeb) {
      FirebaseMassagingHandler.flutterLocalNotificationsPlugin
          .resolvePlatformSpecificImplementation<
              AndroidFlutterLocalNotificationsPlugin>()!
          .createNotificationChannel(FirebaseMassagingHandler.channel);
    }
  }

after that you have to call those functions like this:

  @override
  void initState() {
    firebaseInit().whenComplete(() {
      FirebaseMassagingHandler.config();
    });
    super.initState();
  }
  • Related