当应用程序处于后台或终止时如何重定向用户?

问题描述 投票:0回答:1

我正在我的 Flutter 项目上使用 Flutter Firebase 推送通知。但是,当用户点击通知时,我会将用户重定向到我的主聊天屏幕。当我的应用程序打开时它可以正常工作。但是,当我的应用程序进入后台或终止时,用户在点击打开我的启动屏幕时不会重定向我的主聊天屏幕。

有我正在使用的代码以及我在主聊天屏幕中调用的函数。在我的 main.dart 文件中,我使用了 flutter 后台服务。

main.dart代码

  await Firebase.initializeApp();
  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
  runApp(const MyApp());

@pragma('vm:entry-point')
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  await Firebase.initializeApp();
}
Future<void> setupInteractMessage(BuildContext context) async {
    //when app is terminated.
    RemoteMessage? initialMessage = await FirebaseMessaging.instance.getInitialMessage();
    if (initialMessage != null) {
      handleMessage(context, initialMessage);
    }

    //when app in background.
    FirebaseMessaging.onMessageOpenedApp.listen((event) {
      handleMessage(context, event);
    });
  }

  void handleMessage(BuildContext context, RemoteMessage message) {
    if (message.data['type'] == 'msg') {
      Navigator.of(context).pushNamedAndRemoveUntil(
        MyHome.routeName, (Route<dynamic> route) => false,
      );
    }
  }
flutter dart firebase-cloud-messaging
1个回答
0
投票

我希望对您有所帮助,我在我的应用程序上执行此操作。

final selectNotificationStream = BehaviorSubject<String?>();

 Future<void> init() async {
await createNotificationChannel(_commonChannel);

// When app is closed
// flutter local notification has this method when user tap not
final details = await _flutterLocalNotificationsPlugin
    .getNotificationAppLaunchDetails();
if (details != null && details.didNotificationLaunchApp) {
  String? payload = details.notificationResponse?.payload;
  if (payload?.isNotEmpty ?? false) {
    selectNotificationStream.add(payload);
  }
}

await _flutterLocalNotificationsPlugin.initialize(
  _initializationSettings(),
  onDidReceiveNotificationResponse: _selectNotification,
);

}

然后在您的主页中:

 void initState() {
    super.initState();
      NotificationServices()
        .selectNotificationStream
        .stream
        .listen(goToExecutionPage);
  }

并且在 goToExecutionPage 回调中,您拥有有效负载,并且可以重定向到任何地方。

© www.soinside.com 2019 - 2024. All rights reserved.