使用 Cloud Functions 提醒通知 - Flutter

Heads up notification with Cloud Functions - Flutter

我已经配置了我的 flutter 应用程序以接收推送通知,当我从 FCM 尝试时它工作正常并且当应用程序处于 foreground/background/closed.

时我收到提醒通知

我还配置了频道和所有作品。

问题是当我想使用 Google 云功能发送自动通知时,我从来没有收到提醒通知n。

在我的代码下方:

Main.Dart

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

...

@override
  void initState() {
    LocalNotificationService.initialize(changeMessage);

    /// gives you the message on which user taps and it oened app from terminated state
    FirebaseMessaging.instance.getInitialMessage().then((event) {
      setState(() {
        widget.message = event!.data["route"];
      });
    });
    //foreground
    FirebaseMessaging.onMessage.listen((event) {
      print(event.notification?.body);
      print(event.notification?.title);
      LocalNotificationService.display(event);
    });

    // app in background but opened and user taps on notification
    FirebaseMessaging.onMessageOpenedApp.listen((event) {
      setState(() {
        widget.message = event!.data["route"];
      });
      /*final routeFromMessage =  event.data["route"];
      print(routeFromMessage);
      Navigator.of(context).pushNamed(routeFromMessage);*/
    });

  }
 

在清单中我有:

<meta-data
                android:name="com.google.firebase.messaging.default_notification_channel_id"
                android:value = "myChannel"
                />

我创建了服务

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

class LocalNotificationService{

  static final FlutterLocalNotificationsPlugin _notificationsPlugin= FlutterLocalNotificationsPlugin();

  static void initialize(Function updateRoute){
    final InitializationSettings initializationSettings =
    InitializationSettings(android: AndroidInitializationSettings("@mipmap/ic_launcher"));

    _notificationsPlugin.initialize(initializationSettings,onSelectNotification: (String? route) async{
    updateRoute(route);
    });
  }
 static void display(RemoteMessage remoteMessage) async{
    try {
      final id = DateTime.now().millisecondsSinceEpoch ~/1000;
      final NotificationDetails notificationDetails = NotificationDetails(
        android: AndroidNotificationDetails(
          "myChannel",
          "myChannel channel",
          importance: Importance.max,
          priority: Priority.high
        )
      );
      
      await _notificationsPlugin.show(
          id, remoteMessage.notification!.title, remoteMessage.notification!.body, notificationDetails,payload: remoteMessage.data["route"]);
    } on Exception catch (e) {
      print(e);
    }
 }
}

和我的云函数:

const functions = require("firebase-functions");
const admin = require("firebase-admin");

admin.initializeApp(functions.config().functions);


exports.messageTrigger = functions.firestore.document('events/{likedId}').onCreate(async (snap,context) => { 
    console.log('----------------start function--------------------')
    const doc = snap.data()
    console.log(doc)
    const idFrom = doc.idFrom //chi mette like
    const idTo = doc.idTo //creatore evento
    const activity = doc.activity
    console.log(`Recupero il TO`)
    const res = await admin
      .firestore()
      .collection('users')
      .where('uid', '==', idTo)
      .get()
      .then(querySnapshot => {
        querySnapshot.forEach(userTo => {
          console.log(`Found user to: "${userTo.data().surname}"`)
          console.log(`Recupero il FROM`)
          if (userTo.data().pushToken) {
            // Get info user from (sent)

           admin
              .firestore()
              .collection('users')
              .where('uid', '==', idFrom)
              .get()
              .then(querySnapshot2 => {
                querySnapshot2.forEach(userFrom => {
                  console.log(`Found user from: ${userFrom.data().name}`)
                  const payload = {
                    notification: {
                      title: ...,
                      body: ...,
                      channel_id: "myChannel",
                    },
                    data: {route: ...}
                  }
                  // Let push to the target device
                 admin
                    .messaging()
                    .sendToDevice(userTo.data().pushToken, payload)
                    .then(response => {
                      console.log('Successfully sent message:', response)
                    })
                    .catch(error => {
                      console.log('Error sending message:', error)
                    })
                })
              })
          } else {
            console.log('Can not find pushToken target user')
          }
        })
      })
    return null
});
// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
//
// exports.helloWorld = functions.https.onRequest((request, response) => {
//   functions.logger.info("Hello logs!", {structuredData: true});
//   response.send("Hello from Firebase!");
// });

我怎么解决,

谢谢

对于未来的读者,我通过在我的云函数中使用 android_channel_id: "myChannel" 而不是 channel_id: "myChannel" 来解决它