The idea is that when the app is in foreground, I want to show an alert dialog and when the user presses the okay button from the dialog, it navigates them to a different screen. However, the alterdialog does not appear. If I remove the alertdialog and just keep the navigation code, then the app navigates to a different screen as soon as the notification arrives. This is a bad user experience since the user does not have control of the UI. I want the user to confirm that that they want to navigate to different screen. Hence the use of alertdialog.
Here's my code:
void initState(){
super.initState();
var initializationSettingsAndroid = AndroidInitializationSettings('@drawable/splash');
var initializationSettings = InitializationSettings(android:initializationSettingsAndroid);
flutterLocalNotificationsPlugin.initialize(initializationSettings);
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
print('Inside onmessage');
RemoteNotification notification = message.notification;
AndroidNotification android = message.notification?.android;
if (notification != null && android != null) {
flutterLocalNotificationsPlugin.show(
notification.hashCode,
notification.title,
notification.body,
NotificationDetails(
android: AndroidNotificationDetails(
channel.id,
channel.name,
channel.description,
icon: '@drawable/splash',
playSound: true
),
));
AlertDialog(
title:Text(notification.title),
actions: <Widget>[
TextButton(
child: Text('Cancel'),
onPressed: () {
setState(() {
//Navigator.of(context).pop();
navigatorKey.currentState.push(
MaterialPageRoute(builder: (_) => OrdersScreen()));
});
}),
],
content:SingleChildScrollView(
child:
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children:[
Text(notification.body)
]
)
)
);
}
});
}
Your code just expresses the AlertDialog
but it does not do anything with it. That's why it does not show up.
Solution:
You need to call showDialog and pass it the AlertDialog
object like below:
final AlertDialog alertDialog = AlertDialog(
title: Text(notification.title),
actions: <Widget>[
TextButton(
child: Text('Cancel'),
onPressed: () {
setState(() {
//Navigator.of(context).pop();
navigatorKey.currentState
.push(MaterialPageRoute(builder: (_) => OrdersScreen()));
});
}),
],
content: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [Text(notification.body)])));
showDialog(
context: context// (or `navigatorKey.currentContext` in this case),
builder: (BuildContext context) {
return alertDialog;
},
);