Flutter Awesome通知中,点击通知时如何定向页面

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

我正在使用很棒的通知开发一个 flutter 应用程序。现在我想在单击通知时将导航定向到特定页面。

我尝试了很多方法,但仍然不起作用。我想要导航的页面是目前无状态的Notification_page。我也想在该页面中显示该通知。

android flutter awesome-notifications
2个回答
0
投票

我正在使用

flutter_local_notification

这是我的代码

   @pragma('vm:entry-point')
Future<void> notificationTapBackground(NotificationResponse notificationResponse) async {
  await Firebase.initializeApp();

  // handle action
  await handleNotificationClick(notificationResponse.payload!);

  print('Handling a background message');

  // showToast("${notificationResponse.payload}");
}

handleNotificationClick(String dataStr) async {
  Map<String, dynamic> map = jsonDecode(dataStr);

  if (map["notificationType"].toString().compareTo(NotificationType.StockSell.name.toString()) == 0 || map["notificationType"].toString().compareTo(NotificationType.StockBuy.name.toString()) == 0) {
    Navigator.push(navState.currentContext!,
        CupertinoPageRoute(builder: (context) => const TransactionDetailPage(), settings: RouteSettings(arguments: NotificationArguments(false, map["id"].toString(), map["notificationId"].toString()))));
  } else if (map["notificationType"].toString().compareTo(NotificationType.RecommendationCreated.name.toString()) == 0) {
    if (HydratedBloc.storage.read(Constant.USER_LOGIN) == true) {
      Navigator.push(navState.currentContext!,
          CupertinoPageRoute(builder: (context) => const NotificationsPage(), settings: RouteSettings(arguments: NotificationArguments(false, map["id"].toString(), map["notificationId"].toString()))));
    } else {
      Navigator.pushReplacement(navState.currentContext!, CupertinoPageRoute(builder: (context) => const DashboardPage2()));
    }
  }
}

class NotificationUtils {
  static final _notifications = FlutterLocalNotificationsPlugin();

  static Future init() async {
    AndroidInitializationSettings android = const AndroidInitializationSettings('@mipmap/ic_launcher');

    final DarwinInitializationSettings ios = DarwinInitializationSettings(
        requestSoundPermission: true,
        requestBadgePermission: true,
        requestAlertPermission: true,
        defaultPresentSound: true,
        defaultPresentAlert: true,
        defaultPresentBadge: true,
        onDidReceiveLocalNotification: (a, b, c, d) {
          print("onDidReceiveLocalNotification");
        });

    InitializationSettings settings = InitializationSettings(android: android, iOS: ios);

    _notifications.initialize(
      settings,
      onDidReceiveNotificationResponse: (NotificationResponse notificationResponse) async {
        handleNotificationClick(notificationResponse.payload!);
      },
      onDidReceiveBackgroundNotificationResponse: notificationTapBackground,
    );

    final bool? result = await _notifications.resolvePlatformSpecificImplementation<IOSFlutterLocalNotificationsPlugin>()?.requestPermissions(
          alert: true,
          badge: true,
          sound: true,
        );
  }

  static Future showNotification({required int id, required String notificationType, required String title, required String body, required String payload}) async => _notifications.show(
        id,
        title,
        body,
        await _notificationDetails(notificationType),
        payload: payload,
      );

  static Future _notificationDetails(String notificationType) async {
    AndroidNotificationDetails androidPlatformChannelSpecifics = const AndroidNotificationDetails(
      'high_importance_channel', // id
      'High Importance Notifications', // title
      channelDescription: 'This channel is used for important notifications.',
      // description
      importance: Importance.max,
      priority: Priority.high,
      sound: RawResourceAndroidNotificationSound('slow_spring_board'),
      playSound: true,
      visibility: NotificationVisibility.public,
      // vibrationPattern: vibrationPattern,
      enableLights: true,
      enableVibration: true,
    );

    await _notifications.resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>()?.createNotificationChannel(const AndroidNotificationChannel(
          'high_importance_channel', // id
          'High Importance Notifications', // title
          description: 'This channel is used for important notifications.', // description
          importance: Importance.high,
        ));

    DarwinNotificationDetails iOSPlatformChannelSpecifics = const DarwinNotificationDetails(sound: 'slow_spring_board.aiff', presentSound: true, presentAlert: true, presentBadge: true);

    return NotificationDetails(
      android: androidPlatformChannelSpecifics,
      iOS: iOSPlatformChannelSpecifics,
    );
  }
}

这个类我已经在 Main.dart 中初始化了

NotificationUtils.init();

嗯,据我所知,awesome_notification中的实现过程相同,只需查看更新的Awesome通知文档,我希望我的回答能为您提供实现的上下文

谢谢!!快乐编码


0
投票

要理解这一点,请确保您了解 fcm 和很棒的通知,因为我省略了一些内容。包括他们会让这篇文章变得很长。

如果应用程序收到 fcm 推送通知时正在创建很棒的通知。您可以像这样创建一个前台监听器和一个后台监听器 -

// foreground listener
Future<void> _fcmSetup() async {
  final fcm = FirebaseMessaging.instance;
  await fcm.requestPermission();
  FirebaseMessaging.onMessage.listen(
    (RemoteMessage message) async {
      await _messageHandler(message);
    },
  );
}

// background handler NB: make sure to register this bg handler 
@pragma('vm:entry-point')
Future<void> _fcmBackgroundHandler(RemoteMessage message) async {
  await _messageHandler(message);
}

// the messageHandler
Future<void> _messageHandler(RemoteMessage message) async {
  final String? messageBody = message.notification.body;
  final prefs = await SharedPreferences.getInstance();
  await prefs.setString('messageBody', messageBody);
}

// you  can register your background handler in your main method -
FirebaseMessaging.onBackgroundMessage(_fcmBackgroundHandler);

class NotificationController {
  // Use this method to detect when a new notification is clicked
  @pragma("vm:entry-point")
  static Future<void> onActionReceivedMethod(
      ReceivedAction receivedAction) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.reload();
    final String? messageBody = prefs.getString('messageBody');
    Navigator.of(YourApp.navigatorKey.currentContext!).push(
        MaterialPageRoute(
          builder: (context) => const NotificationPage(),
        ),
      );
}
// in your main method, you should also do this
AwesomeNotifications().setListeners(
    onActionReceivedMethod: NotificationController.onActionReceivedMethod,
);

如果您不使用 fcm 推送通知。无需担心前台和后台听众。您所要做的就是创建NotificationController 类并确保设置其侦听器。

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