Flutter 很棒的通知点击打开特定页面

发布于 2025-01-17 01:14:54 字数 73 浏览 0 评论 0原文

我正在使用 Flutter 很棒的通知。当应用程序关闭时单击通知时,我想将其定向到应用程序内的特殊页面。对我来说最简单的方法是什么?

I am using Flutter awesome notifications. When the notification is clicked when the application is closed, I want to direct it to a special page within the application. What is the easiest way for me to do this?

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

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

发布评论

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

评论(2

苍风燃霜 2025-01-24 01:14:54

为此,首先您需要在 runApp< 之前初始化 AwesomeNotifications /code> 然后简单地放置一个 listner 来监听通知点击:

初始化:

AwesomeNotifications().initialize(
        'resource://drawable/logo_circle_notification',
        [
          NotificationChannel(
              channelGroupKey: 'normal_channel_group',
              channelKey: 'normal_channel',
              channelName: 'Normal Notifications',
              channelDescription: 'Notification channel for normal notifications',
              defaultColor: const Color(0xFF9D50DD),
              ledColor: Colors.white
          ),
        ],
        channelGroups: [
          NotificationChannelGroup(
              channelGroupkey: 'basic_channel_group',
              channelGroupName: 'Basic group'),
        ],
        debug: true
    );

监听:

listenActionStream(){
        AwesomeNotifications().actionStream.listen((receivedAction) {
          var payload = receivedAction.payload;
    
          if(receivedAction.channelKey == 'normal_channel'){
            //do something here
          }
        });
      }

您可以在导航之前将该列表器放在启动屏幕的 initState 中或其他位置到应用程序的主屏幕。

To do this, firstly you need to initialize AwesomeNotifications before runApp and then simply put a listner to listen to the notification click:

Initialize:

AwesomeNotifications().initialize(
        'resource://drawable/logo_circle_notification',
        [
          NotificationChannel(
              channelGroupKey: 'normal_channel_group',
              channelKey: 'normal_channel',
              channelName: 'Normal Notifications',
              channelDescription: 'Notification channel for normal notifications',
              defaultColor: const Color(0xFF9D50DD),
              ledColor: Colors.white
          ),
        ],
        channelGroups: [
          NotificationChannelGroup(
              channelGroupkey: 'basic_channel_group',
              channelGroupName: 'Basic group'),
        ],
        debug: true
    );

Listen:

listenActionStream(){
        AwesomeNotifications().actionStream.listen((receivedAction) {
          var payload = receivedAction.payload;
    
          if(receivedAction.channelKey == 'normal_channel'){
            //do something here
          }
        });
      }

you can put that lister in the initState of your splash screen or something before navigating to Home Screen of the app.

狂之美人 2025-01-24 01:14:54

因为 actionStream 在 AwesomeNotification() 中不再可用
我想提出一个不同的解决方案

NotificationController

class NotificationController {
  static ReceivedAction? initialAction;
  static Future<void> initializeLocalNotifications() async {
    await AwesomeNotifications().initialize(
      "resource://drawable/ic_bg_service_small",
      [
        NotificationChannel(
          channelKey: "notificationChannelId",
          channelName: "channelName",
          channelDescription: "channelName",
          playSound: true,
          onlyAlertOnce: true,
          importance: NotificationImportance.High,
          defaultPrivacy: NotificationPrivacy.Private,
          defaultColor: Colors.blue,
          ledColor: Colors.blue,
          icon: "resource://drawable/ic_bg_service_small",
        )
      ],
      debug: true,
    );

    // Get initial notification action is optional
    initialAction = await AwesomeNotifications()
        .getInitialNotificationAction(removeFromActionEvents: false);
  }

  static Future<void> startListeningNotificationEvents() async {
    AwesomeNotifications().setListeners(
      onActionReceivedMethod: onActionReceivedMethod,
    );
  }

  @pragma('vm:entry-point')
  static Future<void> onActionReceivedMethod(
      ReceivedAction receivedAction) async {
    if (receivedAction.actionType == ActionType.SilentAction) {
      if (receivedAction.payload != null) {
        //////////////////////////////
        print(receivedAction.payload!["payload"]!);
        ////////////////////////////
      }
    } else {
      if (receivedAction.payload != null) {
        ////////////////////////
        print(receivedAction.payload!["payload"]!);
      }
    }
  }
}

Main

Future<void> main() async {
  await NotificationController.initializeLocalNotifications();
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

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

class _MyAppState extends State<MyApp> {
  late ReceivedAction? receivedAction;

  @override
  void initState() {
    NotificationController.startListeningNotificationEvents();
    receivedAction = NotificationController.initialAction;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      debugShowCheckedModeBanner: false,
      home: receivedAction!.payload == null
          ? NotificationPage(
              receivedAction: receivedAction,
            )
          : HomePage(),
    );
  }
}

class HomePage extends StatelessWidget {
  const HomePage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Home page"),
      ),
      body: const Column(
        children: [
          Text("Home page"),
        ],
      ),
    );
  }
}

class NotificationPage extends StatelessWidget {
  const NotificationPage({super.key, this.receivedAction});
  final ReceivedAction? receivedAction;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Notification page"),
      ),
      body: Column(
        children: [
          Text("Notification page: ${receivedAction!.payload}"),
        ],
      ),
    );
  }
}

我建议将有效负载保存在SharedPreference中并在NotificationPage之后清除它

since actionStream isn't available anymore in AwesomeNotification()
i would like to propose a different solution

NotificationController

class NotificationController {
  static ReceivedAction? initialAction;
  static Future<void> initializeLocalNotifications() async {
    await AwesomeNotifications().initialize(
      "resource://drawable/ic_bg_service_small",
      [
        NotificationChannel(
          channelKey: "notificationChannelId",
          channelName: "channelName",
          channelDescription: "channelName",
          playSound: true,
          onlyAlertOnce: true,
          importance: NotificationImportance.High,
          defaultPrivacy: NotificationPrivacy.Private,
          defaultColor: Colors.blue,
          ledColor: Colors.blue,
          icon: "resource://drawable/ic_bg_service_small",
        )
      ],
      debug: true,
    );

    // Get initial notification action is optional
    initialAction = await AwesomeNotifications()
        .getInitialNotificationAction(removeFromActionEvents: false);
  }

  static Future<void> startListeningNotificationEvents() async {
    AwesomeNotifications().setListeners(
      onActionReceivedMethod: onActionReceivedMethod,
    );
  }

  @pragma('vm:entry-point')
  static Future<void> onActionReceivedMethod(
      ReceivedAction receivedAction) async {
    if (receivedAction.actionType == ActionType.SilentAction) {
      if (receivedAction.payload != null) {
        //////////////////////////////
        print(receivedAction.payload!["payload"]!);
        ////////////////////////////
      }
    } else {
      if (receivedAction.payload != null) {
        ////////////////////////
        print(receivedAction.payload!["payload"]!);
      }
    }
  }
}

Main

Future<void> main() async {
  await NotificationController.initializeLocalNotifications();
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

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

class _MyAppState extends State<MyApp> {
  late ReceivedAction? receivedAction;

  @override
  void initState() {
    NotificationController.startListeningNotificationEvents();
    receivedAction = NotificationController.initialAction;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      debugShowCheckedModeBanner: false,
      home: receivedAction!.payload == null
          ? NotificationPage(
              receivedAction: receivedAction,
            )
          : HomePage(),
    );
  }
}

class HomePage extends StatelessWidget {
  const HomePage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Home page"),
      ),
      body: const Column(
        children: [
          Text("Home page"),
        ],
      ),
    );
  }
}

class NotificationPage extends StatelessWidget {
  const NotificationPage({super.key, this.receivedAction});
  final ReceivedAction? receivedAction;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Notification page"),
      ),
      body: Column(
        children: [
          Text("Notification page: ${receivedAction!.payload}"),
        ],
      ),
    );
  }
}

I would advice to save payload in SharedPreference and clear it after the NotificationPage

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