3

i have implemented firebase push notification in my project with payload json, I have done all the configurations and now when i click on the notification, it works sometimes perfectly but sometimes the redirection just doesn't work, let's say if i click the notification 10 times, it redirects to the desired page for 4 times and rest 6 times, its taking me to home screen. I am sharing my code below.

Main File

Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
DartPluginRegistrant.ensureInitialized();
await Firebase.initializeApp();
await SharedPref.initialize();
initilizeCamera();
initializeDb();

FlutterError.onError = (error) {
FirebaseCrashlytics.instance.recordFlutterFatalError(error);
};

PlatformDispatcher.instance.onError = (error, stack) {
FirebaseCrashlytics.instance.recordError(error, stack, fatal: true);
return true;
};
SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp])
.then((_) {
runApp(
const ProviderScope(child: MyApp()),
);
});

await pushNotificationToken();

/// Get initial message
await FirebaseMessaging.instance.getInitialMessage();

notificationActions(
action: (RemoteMessage? message) {
if (kDebugMode) {
if (message?.notification != null) {
      
}
}
if (message != null) {
notificationAction(message: message);
}
},
localNotification: true,
localNotificationAction: (payload) {
if (kDebugMode) {
     
    }
    notificationAction(payload: payload);
  });


SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
systemNavigationBarColor: Colors.white,
statusBarColor: Colors.white,
));
}

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

// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return KeyboardDismissOnTap(
  child: GetMaterialApp(
      theme: appThemeData,
      debugShowCheckedModeBanner: false,
      title: 'XYZ',
      // Start the app with the "/" named route. In this case, the app starts
      // on the FirstScreen widget.
      initialRoute: '/',
      initialBinding:XYZBindings(),
      routes: {
        // When navigating to the "/" route, build the FirstScreen widget.
        '/': (context) => const XYZScreen(),
      }),
  );
 }
 }

Firebase Notification Code

/// Firebase messaging instance
FirebaseMessaging _firebaseMessaging = FirebaseMessaging.instance;

/// Get firebase notification instance
FirebaseMessaging get firebaseMessagingInstance => _firebaseMessaging;

/// Firebase push notification token
Future<String?> pushNotificationToken() async =>
_firebaseMessaging.getToken().then((value) {
  Log.w('FCM TOKEN :: $value');
  return value;
});

/// When user clicks on the notification
void notificationActions({
@required Function(RemoteMessage?)? action,
bool localNotification = false,
Function(Map<String, dynamic>)? localNotificationAction,
}) {
/// Make sure localNotification is Not Null
if (localNotification) {
assert(localNotificationAction != null);
}

if (Platform.isIOS) {
_requestPermissions();
}

if (localNotification) {
FlutterLocalNotificationHelper().initializeSettings(
  actionCallback: localNotificationAction,
);
}

/// Get initial message
_firebaseMessaging.getInitialMessage().then((RemoteMessage? message) {
action!(message);
});

/// On Message
FirebaseMessaging.onMessage.listen((RemoteMessage message) async {
if (localNotification) {
  await FlutterLocalNotificationHelper().showNotificationWithDefaultSound(
    title: message.notification?.title,
    body: message.notification?.body,
    payload: jsonEncode(message.data),
  );
}
});

/// On Message open app
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
action!(message);
});
}

/// Request permission for iOS
void _requestPermissions() {
_firebaseMessaging.requestPermission(
provisional: true,
);
}

Local Notification Page

/// Helper class for local notifications
class FlutterLocalNotificationHelper {
/// Constructor
factory FlutterLocalNotificationHelper() => _instance;

FlutterLocalNotificationHelper._();

/// Flutter LocalNotification Helper instance
static final FlutterLocalNotificationHelper _instance =
  FlutterLocalNotificationHelper._();

/// Flutter LocalNotification for iOS Category
static const String darwinNotificationCategory = 'plainCategory';

/// Notification plugin
late FlutterLocalNotificationsPlugin _flutterLocalNotificationsPlugin;

/// Flutter LocalNotifications Plugin
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
  FlutterLocalNotificationsPlugin();

 /// Request local notification
Future<void> requestLocalNotification() async {
await flutterLocalNotificationsPlugin
    .resolvePlatformSpecificImplementation<
        AndroidFlutterLocalNotificationsPlugin>()
    ?.requestPermission();
  }

 /// local notification plugin callback
 late Function(Map<String, dynamic>) _localNotificationCallback;

 /// Initialize local notifications
 Future<void> initializeSettings({
 @required Function(Map<String, dynamic>)? actionCallback,
 }) async {
 if (actionCallback != null) {
  _localNotificationCallback = actionCallback;
 }

 /// initialize settings for => Android
 const AndroidInitializationSettings initializationSettingsAndroid =
    AndroidInitializationSettings('@mipmap/ic_launcher');

 /// initialize settings for => iOS
 const DarwinInitializationSettings initializationSettingsIOS =
    DarwinInitializationSettings(
  requestSoundPermission: false,
  requestBadgePermission: false,
  requestAlertPermission: false,
  );

  /// Initialize settings for both => Android / iOS
  const InitializationSettings initializationSettings =
    InitializationSettings(
  android: initializationSettingsAndroid,
  iOS: initializationSettingsIOS,
  );

  /// Flutter local notification plugin
  _flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();

  /// Local notification plugin initialize
  await _flutterLocalNotificationsPlugin.initialize(
  initializationSettings,
  onDidReceiveNotificationResponse: (NotificationResponse response) {
    if (response.payload != null) {
      _localNotificationCallback(json.decode(response.payload!));
    }
  
    },
  
    );

   /// On notification click
   final NotificationAppLaunchDetails? notificationAppLaunchDetails =
    await _flutterLocalNotificationsPlugin
        .getNotificationAppLaunchDetails();

   if (notificationAppLaunchDetails?.didNotificationLaunchApp ?? false) {
   await onSelectNotification(
    notificationAppLaunchDetails?.notificationResponse.toString(),
   );
   }
   }

  /// WHEN USER CLICKS TO NOTIFICATION
  Future<void> onSelectNotification(String? payload) async {

  if (payload != null) {
  final Map<String, dynamic> payloadJson =
      jsonDecode(payload) as Map<String, dynamic>;
  _localNotificationCallback(payloadJson);
  }
  }




 /// SHOW LOCAL NOTIFICATION
 /// 'your channel id', 'your channel name', IS NOT NEEDED
 Future<void> showNotificationWithDefaultSound({
 @required String? title,
 @required String? body,
 @required String? payload,
 }) async {
 /// Android notification details
 const AndroidNotificationDetails androidPlatformChannelSpecifics =
    AndroidNotificationDetails(
  'your channel id',
  'your channel name',
  importance: Importance.max,
  priority: Priority.high,
  color: AppColors.red,
  icon: '@mipmap/ic_launcher',
  );

  /// iOS Notification details
  const DarwinNotificationDetails iOSPlatformChannelSpecifics =
    DarwinNotificationDetails(
  categoryIdentifier: darwinNotificationCategory,
  presentSound: true,
  presentAlert: true,
  badgeNumber: 0,
  );

  /// Notification platforms details
  const NotificationDetails platformChannelSpecifics = NotificationDetails(
  android: androidPlatformChannelSpecifics,
  iOS: iOSPlatformChannelSpecifics,
  );

  /// Show notification
  await _flutterLocalNotificationsPlugin.show(
  0,
  title,
  body,
  platformChannelSpecifics,
  payload: payload,
  );
  }
  }

Notifications Action page

void notificationAction(
{RemoteMessage? message, Map<String, dynamic>? payload}) {


The redirection is written here.

 }

please let me know that why sometimes the redirection works and sometimes not.

0 Answers0