how to make "awsome_notification" notification can be push to another page. (offilne App)

1.6k Views Asked by At

I want to use the awesome_notifications package in my Flutter app to create a notification that can navigate to another page when the user taps on it. I'm able to create and display the notification, but I'm not sure how to handle the tap event and navigate to the desired page. How can I do this using awesome_notifications?

my Code:

import 'package:flutter/material.dart';
import 'package:awesome_notifications/awesome_notifications.dart';
import 'package:workout_traker/main.dart';

class NotificationService {
  Future<void> initNotification() async {
    await AwesomeNotifications().initialize(
      null,
      [
        NotificationChannel(
          channelShowBadge: true,
          channelKey: 'basic_channel',
          enableVibration: true,
          channelName: 'Basic notifications',
          channelDescription: 'Notification channel for basic tests',
          defaultColor: const Color(0xFF9D50DD),
          ledColor: Colors.white,
          importance: NotificationImportance.Max,
          onlyAlertOnce: true,
          playSound: true,
          criticalAlerts: true,
        ),
      ],
    );
  }

  Future<void> showNotification(
    int id,
    String title,
    String body,
    int hours,
    int minutes,
    String notificationImage,
    BuildContext context,
  ) async {
    await AwesomeNotifications().createNotification(
      content: NotificationContent(
        id: id,
        channelKey: 'basic_channel',
        title: title,
        body: body,
        bigPicture: 'asset://$notificationImage',
        wakeUpScreen: true,
        backgroundColor: Colors.deepOrange,
        notificationLayout: NotificationLayout.BigPicture,
      ),
      schedule: NotificationCalendar.fromDate(
        date: DateTime.now().add(Duration(hours: hours, minutes: minutes)),
        allowWhileIdle: true,
      ),
    );
  }
}

please help me guys!.

I already try asking chatGbt and all this what he give me , there is an error in

AwesomeNotifications().actionStream.listen((action){//...}
1

There are 1 best solutions below

1
bulgarian-beast On

I've implemented this feature in multiple Flutter apps and would be happy to help you troubleshoot. To debug this issue, follow these steps:

1. Verify Notification Reception:

  • First, confirm whether you're receiving the notifications at all. Ensure that your notifications are being sent correctly and that your device is set up to receive them.

2. Check Click Action:

  • After receiving a notification, check if you can print something when you click on it. This will help determine whether the click action is working as expected.

3. Android vs. iOS Differences:

  • Pay attention to any differences between Android and iOS behavior. Flutter apps can have platform-specific nuances, so knowing whether the issue is platform-specific can be crucial.

Important Note: Make sure you have added the following code to your android/app/src/main/AndroidManifest.xml file:

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

This code is essential for handling notification clicks in your Flutter app. Without it, your app might not respond to notification clicks as expected.

To implement notification handling in your Flutter app using Awesome Notifications and Firebase Cloud Messaging (FCM), follow these steps:

1. Initialize the Notification Channel:

Before handling notifications, ensure that you have initialized the notification channel. This should be done at the app's startup, typically in the main function:

await AwesomeNotifications().initialize(
  null,
  [
    NotificationChannel(
      channelShowBadge: true,
      channelKey: "channel",
      defaultColor: Colors.blue,
      channelName: "Basic Notifications",
      importance: NotificationImportance.High,
      channelDescription: "Description",
    ),
  ],
);

This code sets up a notification channel named "Basic Notifications" with high importance and a specified color.

2. Set Up Notification Handling:

To handle notifications and navigate users to the desired page, initialize your notification handler as follows:

await messaging.getInitialMessage().then((msg) {
  return notificationHandler(msg, context: context);
});

FirebaseMessaging.onMessageOpenedApp.listen((msg) async {
  return await notificationHandler(msg, context: context);
});

FirebaseMessaging.onMessage.listen((msg) async {
  return await notificationHandler(msg, context: context);
});

Here, you're using Firebase Messaging to handle various notification scenarios, such as when the app is in the foreground (onMessage) or when the user taps a notification to open the app (onMessageOpenedApp).

3. Create the notificationHandler Function:

In your notificationHandler function, analyze the content of the received message (msg) and redirect the user to the desired page. For example:

if (content.channelKey == "channel") {
  doSomething(); // Perform any necessary actions

  if (navigatorKey.currentState != null) {
    navigatorKey.currentState!.pushReplacement(
      PageRouteBuilder(
        pageBuilder: (context, animation1, animation2) =>
            DesiredPage(), // Replace 'DesiredPage' with the actual page you want to navigate to
        transitionDuration: const Duration(milliseconds: 0),
      ),
    );
  }
}

In this code, if the notification is from the "channel" you defined earlier, it performs some actions (you can customize this part and use whatever you want to know if you should push users to your DesiredPage) and uses a navigatorKey to navigate to the desired page (DesiredPage). Using pushReplacement replaces the current page with the new one.

4. Implement a Navigator Key:

To use a navigatorKey in your Flutter app, define it at the top level of your application and assign it to the navigatorKey property of your MaterialApp. For example:

final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      navigatorKey: navigatorKey,
      home: const AutoLogin(), // Replace 'AutoLogin' with your app's home page
    );
  }
}

By setting up the navigatorKey and following these steps, you can efficiently handle notifications and navigate users to the relevant pages in your Flutter app.

If you're still facing issues after verifying these steps, please provide more details about your specific problem, such as code snippets and any error messages you're encountering. With more information, the community can offer more targeted assistance to help you resolve the issue.