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();
```
Flutter app does not read firebase notification data on app launch , but does read on background state
665 Views Asked by Developers If Else Solutions At
1
"Push Notification Service"