【问题标题】:Flutter Cloud Messaging not showing Message info in foregroundFlutter Cloud Messaging 未在前台显示消息信息
【发布时间】:2022-06-14 19:00:26
【问题描述】:

我正在尝试在我的 Flutter 项目中使用 Firebase Cloud Messaging。

我已经在 Firebase 中创建了一个项目,并将我的 Flutter 项目设置为使用 Firebase Cloud Messaging。

这里有 main.dart 代码:

import 'package:fcm_flutter/push_notification.dart';
import 'package:firebase_analytics/firebase_analytics.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'package:overlay_support/overlay_support.dart';


import 'notification_badge.dart';

Future _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  print("Handling a background message: ${message.messageId}");
}

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

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

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {

  static FirebaseAnalytics analytics = FirebaseAnalytics.instance;
  static FirebaseAnalyticsObserver observer =
  FirebaseAnalyticsObserver(analytics: analytics);
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return OverlaySupport(
      child: MaterialApp(
        title: 'Flutter FCM',
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
        home: const MyHomePage(title: 'Flutter FCM'),
      ),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  late int _totalNotifications;
  PushNotification? _notificationInfo;

  late final FirebaseMessaging _messaging;

  @override
  void initState() {
    _totalNotifications = 0;
    registerNotification();
    // Call here
    checkForInitialMessage();

    // For handling notification when the app is in background
    // but not terminated
    FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
      PushNotification notification = PushNotification(
        title: message.notification?.title,
        body: message.notification?.body,
      );
      setState(() {
        _notificationInfo = notification;
        _totalNotifications++;
      });
    });

    super.initState();
  }

  void registerNotification() async {
    // 1. Initialize the Firebase app
    await Firebase.initializeApp();

    // 2. Instantiate Firebase Messaging
    _messaging = FirebaseMessaging.instance;
    FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);

    // 3. On iOS, this helps to take the user permissions
    NotificationSettings settings = await _messaging.requestPermission(
      alert: true,
      badge: true,
      provisional: false,
      sound: true,
    );

    if (settings.authorizationStatus == AuthorizationStatus.authorized) {
      print('User granted permission');
      // TODO: handle the received notifications
      // For handling the received notifications
      FirebaseMessaging.onMessage.listen((RemoteMessage message) {
        // Parse the message received
        PushNotification notification = PushNotification(
          title: message.notification?.title,
          body: message.notification?.body,
        );

        setState(() {
          _notificationInfo = notification;
          _totalNotifications++;
        });
      });
      if (_notificationInfo != null) {
        // For displaying the notification as an overlay
        showSimpleNotification(
          Text(_notificationInfo!.title!),
          leading: NotificationBadge(totalNotifications: _totalNotifications),
          subtitle: Text(_notificationInfo!.body!),
          background: Colors.cyan.shade700,
          duration: Duration(seconds: 2),
        );
      }
    } else {
      print('User declined or has not accepted permission');
    }
  }

  // For handling notification when the app is in terminated state
  checkForInitialMessage() async {
    await Firebase.initializeApp();
    RemoteMessage? initialMessage =
        await FirebaseMessaging.instance.getInitialMessage();

    if (initialMessage != null) {
      PushNotification notification = PushNotification(
        title: initialMessage.notification?.title,
        body: initialMessage.notification?.body,
      );
      setState(() {
        _notificationInfo = notification;
        _totalNotifications++;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Text(
            'App for capturing Firebase Push Notifications',
            textAlign: TextAlign.center,
            style: TextStyle(
              color: Colors.black,
              fontSize: 20,
            ),
          ),
          SizedBox(height: 16.0),
          NotificationBadge(totalNotifications: _totalNotifications),
          SizedBox(height: 16.0),
          // TODO: add the notification text here
          _notificationInfo != null
              ? Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      'TITLE: ${_notificationInfo!.title}',
                      style: TextStyle(
                        fontWeight: FontWeight.bold,
                        fontSize: 16.0,
                      ),
                    ),
                    SizedBox(height: 8.0),
                    Text(
                      'BODY: ${_notificationInfo!.body}',
                      style: TextStyle(
                        fontWeight: FontWeight.bold,
                        fontSize: 16.0,
                      ),
                    ),
                  ],
                )
              : Container(),
        ],
      ),
    );
  }
}

这里有安装在 pubspec.yaml 中的包:

  cupertino_icons: ^1.0.2
  firebase_core: "^1.2.1"
  firebase_messaging: "^10.0.1"
  overlay_support: ^1.2.1
  firebase_analytics: ^9.1.6

我正在使用 Cloud Messaging 控制台发送消息,而我只在 Android Studio 控制台中获得此输出:

D/FLTFireMsgReceiver( 5486): broadcast received for message

但应用程序中的任何消息:

当应用程序处于前台时,我缺少什么来获取消息数据。

当应用处于活动状态但在后台时,它正在启动推送通知。

当应用未关闭时,它正在启动推送通知。

编辑:

消息发送:

【问题讨论】:

    标签: flutter firebase-cloud-messaging


    【解决方案1】:

    只有通知键的消息由系统处理,不会传递到您的应用程序。这意味着为了在应用程序处于活动状态时将消息传递到您的应用程序代码,该消息将需要包含数据密钥。

    有关这方面的更多信息,请参阅 message types 上的 Firebase 云消息传递文档。

    【讨论】:

    • 发送消息时我总是放一个数据键和值,键:click_action,值:FLUTTER_NOTIFICATION_CLICK
    • 您可能希望显示您在问题中发送的消息。
    • 完成,您可能会在我的问题中看到消息
    【解决方案2】:

    在尝试收听消息之前,添加以下行:

    await FirebaseMessaging.instance.getToken();
    

    问题就解决了。

    说实话,我不明白它为什么会起作用,但我会在未来 Insha'Allah 中对其进行更多研究。

    【讨论】:

      猜你喜欢
      • 2018-10-18
      • 1970-01-01
      • 2020-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-11
      • 2014-06-01
      相关资源
      最近更新 更多