简体   繁体   English

单击推送通知时如何处理 Flutter 中的屏幕导航?

[英]How to handle screen navigation in Flutter when clicking on a Push Notification?

I have made this file push_notifications.dart我已经制作了这个文件push_notifications.dart

import 'dart:io';

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';

const AndroidNotificationChannel androidSettings = AndroidNotificationChannel(
    'high_importance_channel', // id
    'High Importance Notifications', // title// description
    importance: Importance.high,
    playSound: true);

var iOSSettings = const IOSInitializationSettings(
  defaultPresentAlert: true,
  defaultPresentBadge: true,
  defaultPresentSound: true,
);

final FlutterLocalNotificationsPlugin localNotification =
    FlutterLocalNotificationsPlugin();

var initializationSettingsAndroid =
    const AndroidInitializationSettings('@mipmap/ic_launcher');

var initializationSettings = InitializationSettings(
  android: initializationSettingsAndroid,
  iOS: IOSInitializationSettings(),
);

var notificationDetails = NotificationDetails(
  android: AndroidNotificationDetails(
    androidSettings.id,
    androidSettings.name,
    importance: Importance.high,
    color: Colors.blue,
    playSound: true,
    icon: '@mipmap/ic_launcher',
  ),
  iOS: IOSNotificationDetails(),
);

class PushNotification {
  static final PushNotification _instance = PushNotification._ctor();

  factory PushNotification() {
    return _instance;
  }

  PushNotification._ctor();

  static init() async {
    FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
    getToken();
    await localNotification
        .resolvePlatformSpecificImplementation<
            AndroidFlutterLocalNotificationsPlugin>()
        ?.createNotificationChannel(androidSettings);

    await localNotification
        .resolvePlatformSpecificImplementation<
            IOSFlutterLocalNotificationsPlugin>()
        ?.initialize(iOSSettings);

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

    await FirebaseMessaging.instance.subscribeToTopic("topic");
  }

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

  static getToken() async {
    await FirebaseMessaging.instance.getToken().then((token) {
      token = token;
      print("Token: $token");
    });
  }

  static void show(String title, String description) {
    localNotification.show(
      0,
      title,
      description,
      notificationDetails,
      payload: '',
    );
  }

  static listen(BuildContext context) {
    FirebaseMessaging.onMessage.listen((RemoteMessage message) {
      print('Just received a notification when app is in background');
      showNotification(message, context);
    });

    FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
      print('Just received a notification when app is opened');
      showNotification(message, context);
    });
  }

  static showNotification(RemoteMessage message, BuildContext context) {
    RemoteNotification? notification = message.notification;
    AndroidNotification? android = message.notification?.android;
    AppleNotification? ios = message.notification?.apple;
    if (notification != null) {
      if (Platform.isIOS) {
        localNotification.show(
          notification.hashCode,
          notification.title,
          notification.body,
          notificationDetails,
        );
      } else {
        localNotification.show(
          notification.hashCode,
          notification.title,
          notification.body,
          notificationDetails,
        );
      }
    }

    if (message.data.containsKey("screen")) {
      Navigator.pushNamed(context, message.data["screen"]);
    }
  }
}

I initialised it in main.dart like this:我在main.dart中初始化它,如下所示:

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );

  // Initialize Firebase Cloud Messaging
  PushNotification.init();
  runApp(MyApp());
}

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

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

class _MyAppState extends State<MyApp> {
  final AppRouter router = AppRouter();

  @override
  void initState() {
    PushNotification.listen(context);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (context) => ThemeCubit(),
      child: BlocBuilder<ThemeCubit, ThemeState>(
        builder: (context, state) {
          return MaterialApp(
            debugShowCheckedModeBanner: false,
            onGenerateRoute: router.generateRoute,
            supportedLocales: AppLocalizations.supportedLocales,
            navigatorKey: navigatorKey,
          );
        },
      ),
    );
  }
}

Push notification only pops up when the app is in background.推送通知仅在应用程序处于后台时弹出。 And this is what I'm sending via firebase这就是我通过 firebase 发送的内容

火力基地

Also I've done changes in AndroidManifest.xml我还对AndroidManifest.xml进行了更改AndroidManifest.xml

I want to navigate to contact-us screen.我想导航到联系我们屏幕。 I have set the route and it's working correctly with Navigator.pushNamed(context, 'contact-us');我已经设置了路线,它与Navigator.pushNamed(context, 'contact-us');一起正常工作. . But somehow it's not working with push notification.但不知何故,它不适用于推送通知。

A few things here:这里有几件事:

1- click_action has to be set to "FLUTTER_NOTIFICATION_CLICK" 1- click_action 必须设置为“FLUTTER_NOTIFICATION_CLICK”

2- click_action has to be set in the data section of a payload 2- click_action 必须在有效载荷的数据部分中设置

DATA='{ "notification": { "body": "this is a body", "title": "this is a title", }, "data": { "click_action": "FLUTTER_NOTIFICATION_CLICK", "sound": "default", "status": "done", "screen": "screenA", }, "to": "<FCM TOKEN>" }' This should allow you to receive the message in the onMessage handler in your flutter app. DATA='{ "notification": { "body": "this is a body", "title": "this is a title", }, "data": { "click_action": "FLUTTER_NOTIFICATION_CLICK", "sound": "default", "status": "done", "screen": "screenA", }, "to": "<FCM TOKEN>" }'这应该允许您在 flutter 应用程序的 onMessage 处理程序中接收消息.

From there you can call Navigator.of(context).pushNamed(message['screen']).从那里你可以调用 Navigator.of(context).pushNamed(message['screen'])。

If you don't have a BuildContext at that point, you can register a GlobalKey as the navigatorKey property of your MaterialApp, and use it to access your Navigator globally, via GlobalKey.currentState如果此时您没有 BuildContext,您可以将 GlobalKey 注册为 MaterialApp 的 navigatorKey 属性,并使用它通过 GlobalKey.currentState 全局访问您的 Navigator

Navigation through notification onTap is listened by FirebaseMessaging.onMessageOpenedApp example code is given below.通过通知 onTap 导航由FirebaseMessaging.onMessageOpenedApp监听,示例代码如下。

 FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
  print('Just received a notification when app is opened');
  showNotification(message, context);
  if(message.notification != null){
    //"route" will be your root parameter you sending from firebase
    final routeFromNotification = message.data["route"];
    if (routeFromNotification != null) {
      routeFromNotification == "profile"?
        Navigator.of(context).pushNamed('profile')
    }
    else {
        developer.log('could not find the route');
      }
  }
});

You need to Provide GlobalKey and use navigation throw navigation Key like below initialise global key in main.dart for navigation without context您需要提供 GlobalKey 并使用如下导航键在 main.dart 中初始化全局键以进行无上下文导航

GlobalKey<NavigatorState> navigatorKey = GlobalKey(debugLabel: "Main Navigator");

Also provide navigator key Material App in navigationKey like below还在 navigationKey 中提供导航键 Material App,如下所示

navigatorKey: navigatorKey,

Use direct navigation using navigationKey and your navigation method in whole app where you want to use like below在您想要使用的整个应用程序中使用 navigationKey 和您的导航方法使用直接导航,如下所示

navigatorKey.currentState!.pushNamed('contact');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM