当我单击Firebase推送通知的前景或背景中的Firebase推送通知时,请导航到另一个屏幕。

发布于 2025-02-06 05:51:08 字数 7371 浏览 2 评论 0 原文

我在“狂图”应用中使用firebase消息传递,当我单击通知时,我想导航到另一个屏幕,即使我的应用在前景或背景中,我都使用了许多功能,并且没有触发点击事件,我找不到一切都可以解决我的问题。

当我在应用程序处于前景或背景时单击通知时,什么也不会发生,因为它导航到同一页面。 当我在终止应用程序时单击通知时,它会在飞溅屏幕上打开,然后转到家中,而不是我想要的屏幕。

我在清单中添加了此 intent-filter

  <intent-filter>
                <action android:name="FLUTTER_NOTIFICATION_CLICK" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>

,然后将其添加到 json 对象中

"click_action": "FLUTTER_NOTIFICATION_CLICK",

,这是我如何在<<<代码> main.dart

const AndroidNotificationChannel channel = AndroidNotificationChannel(
    'high_importance', // id
    'High Importance Notifications', // title
    importance: Importance.high,
    playSound: true);
final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();


Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  SessionManager sessionManager = SessionManager();

  await Firebase.initializeApp();
  //final sound = 'sound.mp3';
  print('A bg message just showed up :  ${message.messageId}');

  final android = AndroidInitializationSettings('@mipmap/ic_launcher');
  final ios = IOSInitializationSettings(
    requestSoundPermission: false,
    requestBadgePermission: false,
    requestAlertPermission: false,);
  final settings = InitializationSettings(android: android,iOS: ios);
  flutterLocalNotificationsPlugin.initialize(settings,);
  if(message.data['title'].toString().toLowerCase()=="new request") {
    sessionManager.getBadge().then((badge) {
      if (badge != null) {
        int x = badge + 1;
        sessionManager.saveBadge(x);
        print("notification number is " + x.toString());
      }
      else {
        sessionManager.saveBadge(1);
      }
    });

  }

  flutterLocalNotificationsPlugin.show(
      message.data.hashCode,
      message.data['title'],
      message.data['body'],
      NotificationDetails(
        android: AndroidNotificationDetails(
          channel.id,
          channel.name,
          importance: Importance.high,
          priority: Priority.high,
         // sound: RawResourceAndroidNotificationSound(sound.split('.').first),
          playSound: true,
          icon: '@mipmap/ic_launcher',
        ),

      ));
  /*NotificationApi.showNotification(
      title: message.data['title'],
      body: message.data['body'],
      payload: "",
      id:  int.parse(channel.id));*/

}


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

  await Firebase.initializeApp();
  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
  await flutterLocalNotificationsPlugin
      .resolvePlatformSpecificImplementation<
      AndroidFlutterLocalNotificationsPlugin>()
      ?.createNotificationChannel(channel);

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

  );
  


  runApp(MyApps());
  // configLoading();

}


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

  @override
  State<StatefulWidget> createState() {
    return MyApp();
  }
}


class MyApp extends State<MyApps> {
  static  ValueNotifier<int> strikeNotifier = ValueNotifier(0);

  Color _primaryColor =  Color(0xff0d8b75);


  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return ScreenUtilInit(
      builder: () => MaterialApp(
        debugShowCheckedModeBanner: false,
        home: SplashScreen(),
      ),
      designSize: const Size(1080, 2280),
    );
  }


  void showNotification(String title, String body) async {
    await _demoNotification(title, body);
  }

  Future<void> _demoNotification(String title, String body) async {
    var androidPlatformChannelSpecifics = AndroidNotificationDetails(
        'channel_I', 'channel name',
        showProgress: true,
        priority: Priority.high,
        playSound: true,
        ticker: 'test ticker');

    var iOSChannelSpecifics = IOSNotificationDetails();
    var platformChannelSpecifics = NotificationDetails(
        android: androidPlatformChannelSpecifics, iOS: iOSChannelSpecifics);
    await flutterLocalNotificationsPlugin
        .show(0, title, body, platformChannelSpecifics, payload: 'test');
  }

  @override
  void initState() {
    super.initState();

       FirebaseMessaging.instance.getInitialMessage().then((RemoteMessage? message) {
  if (message != null) {
    Navigator.push(context, MaterialPageRoute(builder: (context)=>DoneAndPaiedPagess(0)));

  }
});

    getToken().then((value) {
      if(value!=null) {
        AppConstants.firebaseToken = value;
      }
    });


    FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
    new FlutterLocalNotificationsPlugin();
    var initializationSettingsAndroid =  AndroidInitializationSettings('@mipmap/ic_launcher');
    var initializationSettingsIOS =  IOSInitializationSettings();
    var initializationSettings =  InitializationSettings(android: initializationSettingsAndroid, iOS: initializationSettingsIOS);
    flutterLocalNotificationsPlugin.initialize(initializationSettings,
      );



    FirebaseMessaging.onMessage.listen((RemoteMessage message) {
      var data = message.data;
      //  AndroidNotification? android = message.notification?.android;/


      if (data != null ) {
        if(data['title'].toString().toLowerCase()=="new request") {
          SessionManager sessionManager = SessionManager(context);
          sessionManager.getBadge().then((badge) {
            if (badge != null) {
              setState(() {
                int x = badge + 1;
                strikeNotifier.value = x;
                sessionManager.saveBadge(x);
              });
            }
            else {
              strikeNotifier.value = 1;
              sessionManager.saveBadge(1);
            }
          });
        }
        print("entered");
        flutterLocalNotificationsPlugin.show(
            data.hashCode,
            data['title'],
            data['body'],
            NotificationDetails(
              android: AndroidNotificationDetails(
                channel.id,
                channel.name,
                playSound: true,
                icon: '@mipmap/ic_launcher',
              ),
            ));

      }
    });
   FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
  Navigator.push(context, MaterialPageRoute(builder: (context)=>DoneAndPaiedPagess(0)));

});
   
  }

  Future<String?> getToken() async{
    String? token = await FirebaseMessaging.instance.getToken();
    print("token is "+token!);
    return token;

  }
}

in yaml

 firebase_core: ^1.12.0
  firebase_messaging: ^11.2.6
dependency_overrides:
  firebase_messaging_platform_interface: 3.1.6

编辑:从多个解决方案中,我尝试了我使用 onMessageOpenedApp in Initstate 中的最常见解决方案但是它没有进入

FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
      Navigator.push(context, MaterialPageRoute(builder: (context)=>DoneAndPaiedPagess(0)));
    });

I use Firebase messaging in my Flutter app , I want to navigate to another screen when I click on the notification even my app is in foreground or background , I used many functions and it doesn't trigger the click event and I can't find anything can solve my problem .

When I click on the notification when app is in foreground or background , nothing happened because it navigate to the same page .
And when I click on the notification when app is terminated , it opens on Splash screen and go to the home not the screen that I want .

I added this intent-filter in my Manifest

  <intent-filter>
                <action android:name="FLUTTER_NOTIFICATION_CLICK" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>

And I added this to the Json object

"click_action": "FLUTTER_NOTIFICATION_CLICK",

And here is how can I get background FCM in the main.dart

const AndroidNotificationChannel channel = AndroidNotificationChannel(
    'high_importance', // id
    'High Importance Notifications', // title
    importance: Importance.high,
    playSound: true);
final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();


Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  SessionManager sessionManager = SessionManager();

  await Firebase.initializeApp();
  //final sound = 'sound.mp3';
  print('A bg message just showed up :  ${message.messageId}');

  final android = AndroidInitializationSettings('@mipmap/ic_launcher');
  final ios = IOSInitializationSettings(
    requestSoundPermission: false,
    requestBadgePermission: false,
    requestAlertPermission: false,);
  final settings = InitializationSettings(android: android,iOS: ios);
  flutterLocalNotificationsPlugin.initialize(settings,);
  if(message.data['title'].toString().toLowerCase()=="new request") {
    sessionManager.getBadge().then((badge) {
      if (badge != null) {
        int x = badge + 1;
        sessionManager.saveBadge(x);
        print("notification number is " + x.toString());
      }
      else {
        sessionManager.saveBadge(1);
      }
    });

  }

  flutterLocalNotificationsPlugin.show(
      message.data.hashCode,
      message.data['title'],
      message.data['body'],
      NotificationDetails(
        android: AndroidNotificationDetails(
          channel.id,
          channel.name,
          importance: Importance.high,
          priority: Priority.high,
         // sound: RawResourceAndroidNotificationSound(sound.split('.').first),
          playSound: true,
          icon: '@mipmap/ic_launcher',
        ),

      ));
  /*NotificationApi.showNotification(
      title: message.data['title'],
      body: message.data['body'],
      payload: "",
      id:  int.parse(channel.id));*/

}


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

  await Firebase.initializeApp();
  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
  await flutterLocalNotificationsPlugin
      .resolvePlatformSpecificImplementation<
      AndroidFlutterLocalNotificationsPlugin>()
      ?.createNotificationChannel(channel);

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

  );
  


  runApp(MyApps());
  // configLoading();

}


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

  @override
  State<StatefulWidget> createState() {
    return MyApp();
  }
}


class MyApp extends State<MyApps> {
  static  ValueNotifier<int> strikeNotifier = ValueNotifier(0);

  Color _primaryColor =  Color(0xff0d8b75);


  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return ScreenUtilInit(
      builder: () => MaterialApp(
        debugShowCheckedModeBanner: false,
        home: SplashScreen(),
      ),
      designSize: const Size(1080, 2280),
    );
  }


  void showNotification(String title, String body) async {
    await _demoNotification(title, body);
  }

  Future<void> _demoNotification(String title, String body) async {
    var androidPlatformChannelSpecifics = AndroidNotificationDetails(
        'channel_I', 'channel name',
        showProgress: true,
        priority: Priority.high,
        playSound: true,
        ticker: 'test ticker');

    var iOSChannelSpecifics = IOSNotificationDetails();
    var platformChannelSpecifics = NotificationDetails(
        android: androidPlatformChannelSpecifics, iOS: iOSChannelSpecifics);
    await flutterLocalNotificationsPlugin
        .show(0, title, body, platformChannelSpecifics, payload: 'test');
  }

  @override
  void initState() {
    super.initState();

       FirebaseMessaging.instance.getInitialMessage().then((RemoteMessage? message) {
  if (message != null) {
    Navigator.push(context, MaterialPageRoute(builder: (context)=>DoneAndPaiedPagess(0)));

  }
});

    getToken().then((value) {
      if(value!=null) {
        AppConstants.firebaseToken = value;
      }
    });


    FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
    new FlutterLocalNotificationsPlugin();
    var initializationSettingsAndroid =  AndroidInitializationSettings('@mipmap/ic_launcher');
    var initializationSettingsIOS =  IOSInitializationSettings();
    var initializationSettings =  InitializationSettings(android: initializationSettingsAndroid, iOS: initializationSettingsIOS);
    flutterLocalNotificationsPlugin.initialize(initializationSettings,
      );



    FirebaseMessaging.onMessage.listen((RemoteMessage message) {
      var data = message.data;
      //  AndroidNotification? android = message.notification?.android;/


      if (data != null ) {
        if(data['title'].toString().toLowerCase()=="new request") {
          SessionManager sessionManager = SessionManager(context);
          sessionManager.getBadge().then((badge) {
            if (badge != null) {
              setState(() {
                int x = badge + 1;
                strikeNotifier.value = x;
                sessionManager.saveBadge(x);
              });
            }
            else {
              strikeNotifier.value = 1;
              sessionManager.saveBadge(1);
            }
          });
        }
        print("entered");
        flutterLocalNotificationsPlugin.show(
            data.hashCode,
            data['title'],
            data['body'],
            NotificationDetails(
              android: AndroidNotificationDetails(
                channel.id,
                channel.name,
                playSound: true,
                icon: '@mipmap/ic_launcher',
              ),
            ));

      }
    });
   FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
  Navigator.push(context, MaterialPageRoute(builder: (context)=>DoneAndPaiedPagess(0)));

});
   
  }

  Future<String?> getToken() async{
    String? token = await FirebaseMessaging.instance.getToken();
    print("token is "+token!);
    return token;

  }
}

In yaml

 firebase_core: ^1.12.0
  firebase_messaging: ^11.2.6
dependency_overrides:
  firebase_messaging_platform_interface: 3.1.6

Edit : from multiple solutions , I tried the most common solution that I used onMessageOpenedApp in initState but it doesn't enter in it

FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
      Navigator.push(context, MaterialPageRoute(builder: (context)=>DoneAndPaiedPagess(0)));
    });

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

伤感在游骋 2025-02-13 05:51:10

在Initstate内的家中小部件上,检查 getInitialMessage 值:

// get the remote message when your app opened from push notification while in background state
RemoteMessage? initialMessage = await FirebaseMessaging.instance.getInitialMessage();

// check if it is exists
if (initialMessage != null) {
    // check the data property within RemoteMessage and do navigate based on it
}

在此处查看firebase flutter文档 https://firebase.flutter.dev/docs/messaging/notifications/#handling-interaction

On your home widget within initState, check the getInitialMessage value :

// get the remote message when your app opened from push notification while in background state
RemoteMessage? initialMessage = await FirebaseMessaging.instance.getInitialMessage();

// check if it is exists
if (initialMessage != null) {
    // check the data property within RemoteMessage and do navigate based on it
}

Check the firebase flutter documentation here https://firebase.flutter.dev/docs/messaging/notifications/#handling-interaction.

江湖正好 2025-02-13 05:51:10

使用

Use onMessageOpenedApp stream to listen when a notification is opened in the foreground or background. When the application is terminated, use getInitialMessage to get a pending notification.

蓝海似她心 2025-02-13 05:51:10

我不确定这是否有帮助。但是,正如解释的那样 firebase Messaging docs docs docs andling-interaction 和实际的firebase onMessageOpenedApp 当从背景状态打开应用程序时,该流 emeTemessage 。 getInitialMessage 如果将应用程序从终止状态打开 Future 包含 remotemessage 的未来。

您应该遵循GitHub示例上写的代码,并按照自己的方式实施。我希望这会有所帮助。

I am no sure if this helps right now. But as explained Firebase Messaging docs handling-interaction and the actual firebase messaging example in github You should use onMessageOpenedApp A Stream which posts a RemoteMessage when the application is opened from a background state. and getInitialMessage If the application is opened from a terminated state a Future containing a RemoteMessage will be returned.

You should follow the code written on the GitHub example and implement it on your own way. I hope this helps.

﹉夏雨初晴づ 2025-02-13 05:51:09

在代码中,您使用 Flutter_local_notifications 插件,并且在从Firebase消息传递获得推送通知时会创建本地通知。

由于该通知不是由Firebase Messaging创建的,因此您没有在 getInitialMessage onMessageOpenedApp 中点击回调。

为了在本地通知上进行点击回调,您可以在初始化 flutter_local_notifications 时传递回调函数

flutterLocalNotificationsPlugin.initialize(initializationSettings,
    onSelectNotification: onSelectNotification);

void selectNotification(String payload) async {
    if (payload != null) {
      debugPrint('notification payload: $payload');
// Here you can check notification payload and redirect user to the respective screen
      await Navigator.push(
         context,
         MaterialPageRoute<void>(builder: (context) => SecondScreen(payload)),
      );
    }
}

,您可以检查 flutter_local_notifications 文档

In your code, you are using the flutter_local_notifications plugin and you are creating local notification when you get a push notification from firebase messaging.

Since the notification is not created by firebase messaging so, you are not getting on tap callback in getInitialMessage and onMessageOpenedApp.

In order to get on tap callback on local notifications, you can pass a callback function while initializing flutter_local_notifications

flutterLocalNotificationsPlugin.initialize(initializationSettings,
    onSelectNotification: onSelectNotification);

void selectNotification(String payload) async {
    if (payload != null) {
      debugPrint('notification payload: $payload');
// Here you can check notification payload and redirect user to the respective screen
      await Navigator.push(
         context,
         MaterialPageRoute<void>(builder: (context) => SecondScreen(payload)),
      );
    }
}

For more, you can check flutter_local_notifications documentation

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文