0
We used below code for routing through global navigation key in app when a notification is clicked.

>main.dart 
```
void main() async {
  HttpOverrides.global = new MyHttpOverrides();
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  FirebaseDynamicLink.init();
  FirebaseNotification.init();
  const MethodChannel('flavor')
      .invokeMethod('getFlavor')
      .then((String? flavor) {
    print('STARTED WITH FLAVOR $flavor');
    if (flavor == 'PROD') {
      startPROD();
    } else if (flavor == 'UAT') {
      startUAT();
    }
  }).catchError((error) {
    print(error);
    print('FAILED TO LOAD FLAVOR');
  });
  SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp])
      .then((_) {
    runApp(MyApp());
  });
}

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

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

class _MyAppState extends State {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      navigatorKey: AuthNav.navigationKey,
      onGenerateRoute: (RouteSettings settings) {
        return makeRoute(
          context: context,
          routeName: settings.name!,
          arguments: settings.arguments,
        );
      },
    );
  }
}
```

>firebase_notification.dart
```
FirebaseNotification.init() {
    initNotification = InitNotification();
    listenWhenMessageComes();
    listenWhenAppInBackground();
    listenWhenAppOpned();
    listenWhenUserIsOnApp();
  }

Future listenWhenAppOpned() async {
    //When user clickes on notification
    FirebaseMessaging.onMessageOpenedApp.listen((event) async {
      if (event.notification != null) {
        // print(event.notification!.body);
        await initNotification.onNotificationSelected(event.data.toString());
      }
    });
  }

```
`code for routing control by data`
>init_notification.dart
```
Future onNotificationSelected(String? payLoad) async {
    // await NotificationCount.removeCount();
    print(payLoad);
    if (payLoad != null) {
      List str =
          payLoad.replaceAll("{", "").replaceAll("}", "").split(",");
      Map result = {};
      for (int i = 0; i  s = str[i].split(":");
        result.putIfAbsent(s[0].trim(), () => s[1].trim());
      }
      print("result:$result");
      // await goToRespectedPage(result);
    }
  }
```
```
Future goToRespectedPage(Map result) async {
    try {
      var routeName = NotificationRouteModel.fromJson(result).route;
      if (routeName.isNotEmpty) {
        if (userData != null) {
          switch (routeName) {
            case '/ViewPostPage':
              await AuthNav.navigationKey.currentState!.pushReplacementNamed(routeName,
                  arguments: int.parse(result['kmdpWallId']));
              break;
            default:
              await AuthNav.navigationKey.currentState!.pushNamed("/MainPage");
          }
        } else {
          await AuthNav.navigationKey.currentState!.pushNamed("/LoginPage");
        }
      }
    } catch (err, stack) {
      print(err);
      print(stack);
    }
  }
```
>routes.dart
```
makeRoute(
    {required BuildContext context,
    required String routeName,
    Object? arguments}) {
  final PageRoute child =
      _buildRoute(context: context, routeName: routeName, arguments: arguments);
  return child;
}

_buildRoute({
  required BuildContext context,
  required String routeName,
  Object? arguments,
}) {
  switch (routeName) {
    case '/':
      return normalPageRoute(
        context: context,
        page: ChangeNotifierProvider(
          create: (context) => StartScreenProvider(),
          child: StartScreenPage(),
        ),
      );
case '/LoginPage':
      return normalPageRoute(
        context: context,
        page: ChangeNotifierProvider(
          create: (context) => LoginPageProvider(),
          child: LoginPage(),
        ),
      );
    case '/ViewPostPage':
      int kmdpWallId = arguments as int;
      return normalPageRoute(
        context: context,
        page: ChangeNotifierProvider(
          create: (context) => ViewPostPageProvider(kmdpWallId: kmdpWallId),
          child: ViewPostPage(),
        ),
      );

    // case '/AddCommentsPage':
    //   PostData postData = arguments as PostData;
    //   return normalPageRoute(
    //       context: context,
    //       page: ChangeNotifierProvider(
    //           create: (context) => AddCommentsProvider(postData: postData),
    //           child: AddCommentsPage()));
    // case '/':
    // return normalPageRoute(context: context, page: ChangeNotifierProvider(create: create))

    default:
      throw 'Route $routeName is not defined';
  }
}

normalPageRoute({
  required BuildContext context,
  required Widget page,
}) =>
    MaterialPageRoute(
        builder: (BuildContext context) => page,
        maintainState: true,
        fullscreenDialog: false);

```
>auth_nav.dart
```
static final GlobalKey navigationKey =
      GlobalKey();
```

1 Answer 1

0
void main() async {
 WidgetsFlutterBinding.ensureInitialized();
 FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
 await Firebase.initializeApp();
 runApp(Home());
}

Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) 
 async {

   await Firebase.initializeApp();
   InAppNotifications().setStatus(true);
   print("Handling a background message: ${message.messageId}");
   PushNotificationService().navigateToPost(message.data);
 }

"Push Notification Service"

class PushNotificationService {
  final FirebaseMessaging _fcm = FirebaseMessaging.instance;
  final String urlString = dotenv.env["apiUrl"].toString();
  final dataStorage = GetStorage();

 Future initialise() async {
   if (Platform.isIOS) {
    _fcm.requestPermission();
   }

 FirebaseMessaging.onMessage.listen((RemoteMessage message) {
  print('Got a message whilst in the foreground!');
  // print('Message data: ${message.data}');
  Map data = message.data;
  InAppNotifications().setStatus(true);
  // print(screen);
 });

 FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
  navigateToPost(message.data);
 });
 FirebaseMessaging.onBackgroundMessage((message) async {
  navigateToPost(message.data);
  return null;
 });
 }

 final message = await 
  FirebaseMessaging.instance.getInitialMessage();
  if (message == null) {
  return null;
  } else {
  return navigateToPost(message.data);
 }

void navigateToPost(Map<String, dynamic> message) {
   var screen = message["type"];
   print(message);
   }
 }
2
  • All this code is working fine when app is in background state but when the app is in terminated state the data from notification is getting null so because of that i con't get my route name from notification and getting blank screen , So share me your navigation after notification is clicked Commented Jun 22, 2022 at 7:08
  • If you are sending data in notification then you will get your data stored in message variable of push notifications service class Commented Jun 22, 2022 at 7:12

Not the answer you're looking for? Browse other questions tagged or ask your own question.