1

当应用程序打开(前台)并且我收到一条我想导航到屏幕的通知时。其他 2 个案例工作正常(背景和终止)。我正在使用这个例子 https://pub.dev/packages/firebase_messaging/example

请帮助我现在被困在这两天了。我知道我应该在 onMessage.listen 上添加有效负载,但是在我这样做之后?!

    Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  await Firebase.initializeApp();
  print('Handling a background message ${message.messageId}');
}

/// Create a [AndroidNotificationChannel] for heads up notifications
AndroidNotificationChannel channel;

/// Initialize the [FlutterLocalNotificationsPlugin] package.
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin;

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();

  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);

  FirebaseMessaging.instance.getToken().then((value) {
    firebaseToken = value;
    print('firebaseToken $firebaseToken');
  });

  if (!kIsWeb) {
    channel = const AndroidNotificationChannel(
      'high_importance_channel', // id
      'High Importance Notifications', // title
      'This channel is used for important notifications.', // description
      importance: Importance.high,
    );

    flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();

    await flutterLocalNotificationsPlugin
        .resolvePlatformSpecificImplementation<
            AndroidFlutterLocalNotificationsPlugin>()
        ?.createNotificationChannel(channel);

    await FirebaseMessaging.instance
        .setForegroundNotificationPresentationOptions(
      alert: true,
      badge: true,
      sound: true,
    );
  }

  runApp(MyApp());
}

“我的家乡”

      int _messageCount = 0;
  String constructFCMPayload(String token) {
    _messageCount++;
    return jsonEncode({
      'token': token,
      'data': {
        'click_action': 'FLUTTER_NOTIFICATION_CLICK',
        'via': 'FlutterFire Cloud Messaging!!!',
        'count': _messageCount.toString(),
      },
      'notification': {
        'title': 'Hello FlutterFire!',
        'body': 'This notification (#$_messageCount) was created via FCM!',
      },
    });
  }

   @override
  void initState() {
    super.initState();
    FirebaseMessaging.onMessage.listen((RemoteMessage message) {
      RemoteNotification notification = message.notification;
      AndroidNotification android = message.notification?.android;
      if (notification != null && android != null && !kIsWeb) {
        print(message.data);
        print('onMessage method');
        flutterLocalNotificationsPlugin.show(
          notification.hashCode,
          notification.title,
          notification.body,
          NotificationDetails(
            android: AndroidNotificationDetails(
              channel.id,
              channel.name,
              channel.description,
              icon: 'launcher_icon',
            ),
          ),
        );

      }
    });

    FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) async {
      print('A new onMessageOpenedApp event was published!');
      print(message.data);
      print('onMessageOpenedApp method');

      if (loginState && message != null) {
        if (message.data['module'] == 'article') {
          articleID = await message.data['id'];

          Navigator.pushNamed(context, 'ArticleDetails',
              arguments: MessageArguments(message, true));
        } else if (message.data['module'] == 'question') {
          questionID = await message.data['id'];

          Navigator.pushNamed(context, 'QuestionDetails',
              arguments: MessageArguments(message, true));
        } else if (message.data['module'] == 'reservation') {
          Navigator.pushNamed(context, 'Reservations',
              arguments: MessageArguments(message, true));
        } else if (message.data['module'] == 'job') {
          Navigator.pushNamed(context, 'Jobs',
              arguments: MessageArguments(message, true));
        } else if (message.data['module'] == 'addresses') {
          Navigator.pushNamed(context, 'InterestedAddresses',
              arguments: MessageArguments(message, true));
        }
      } else {
        Splash();
      }
    });

    FirebaseMessaging.instance
        .getInitialMessage()
        .then((RemoteMessage message) async {
      if (loginState && message != null) {
        if (message.data['module'] == 'article') {
          articleID = await message.data['id'];

          Navigator.pushNamed(context, 'ArticleDetails',
              arguments: MessageArguments(message, true));
        } else if (message.data['module'] == 'question') {
          questionID = await message.data['id'];

          Navigator.pushNamed(context, 'QuestionDetails',
              arguments: MessageArguments(message, true));
        } else if (message.data['module'] == 'reservation') {
          Navigator.pushNamed(context, 'Reservations',
              arguments: MessageArguments(message, true));
        } else if (message.data['module'] == 'job') {
          Navigator.pushNamed(context, 'Jobs',
              arguments: MessageArguments(message, true));
        } else if (message.data['module'] == 'addresses') {
          Navigator.pushNamed(context, 'InterestedAddresses',
              arguments: MessageArguments(message, true));
        }
      } else {
        Splash();
      }
    });
  }
4

2 回答 2

0

当您在 Android 中显示来自 FCM 消息的本地通知时,您必须配置一个函数来处理这种情况:当 Android 应用程序处于前台时,接收到的消息被点击

因此,在初始化本地通知的位置添加此配置:

await _flutterLocalNotificationsPlugin!.initialize(
  const InitializationSettings(
    android: AndroidInitializationSettings(),
    iOS: IOSInitializationSettings()),
  onSelectNotification: _onSelectNotification);

该函数应如下所示:

Future<dynamic> _onSelectNotification(String? payload) async {
 
}
于 2021-10-04T16:02:31.623 回答
0

您可以尝试在onSelectNotification回调中添加导航,您可以在通知初始化时添加

像这样:

// initialise the plugin. app_icon needs to be a added as a drawable resource to the Android head project
const AndroidInitializationSettings initializationSettingsAndroid =
    AndroidInitializationSettings('app_icon');
final IOSInitializationSettings initializationSettingsIOS =
    IOSInitializationSettings(
        onDidReceiveLocalNotification: onDidReceiveLocalNotification);
final InitializationSettings initializationSettings = InitializationSettings(
    android: initializationSettingsAndroid,
    iOS: initializationSettingsIOS);
flutterLocalNotificationsPlugin.initialize(initializationSettings,
    onSelectNotification: (){
        // Set your navigation code here!!
    },
);
于 2021-10-04T16:32:14.597 回答