To open a particular screen on clicking on a push notification in Flutter, you will need to handle the notification click event and use a navigation package like flutter_local_notifications
to navigate to the desired screen.
Here is an example of how you can achieve this:
1. First, add the flutter_local_notifications
package to your pubspec.yaml
file:
dependencies:
flutter_local_notifications: ^5.0.0
2. Import the necessary packages in your Dart file:
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:flutter/material.dart';
3. Initialize the FlutterLocalNotificationsPlugin
in your main.dart
file:
final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
4. Set up the notification configuration in the main.dart
file:
Future
WidgetsFlutterBinding.ensureInitialized();
// Create an instance of initialization settings
final InitializationSettings initializationSettings =
InitializationSettings(android: AndroidInitializationSettings('@mipmap/ic_launcher'));
// Initialize the FlutterLocalNotificationsPlugin with the initialization settings
await flutterLocalNotificationsPlugin.initialize(
initializationSettings,
onSelectNotification: (String? payload) async {
if (payload != null) {
// Handle the notification payload and navigate to the desired screen
Navigator.pushNamed(context, '/desired-screen');
}
},
);
runApp(MyApp());
}
5. Handle the notification in the background or foreground (inside your notification handling code):
Future
const AndroidNotificationDetails androidPlatformChannelSpecifics =
AndroidNotificationDetails('your channel id', 'your channel name', 'your channel description',
importance: Importance.max, priority: Priority.high, ticker: 'ticker');
const NotificationDetails platformChannelSpecifics =
NotificationDetails(android: androidPlatformChannelSpecifics);
await flutterLocalNotificationsPlugin.show(
0,
'Notification title',
'Notification body',
platformChannelSpecifics,
payload: payload,
);
}
Note that in the above code, the onSelectNotification
callback is triggered when the user clicks on the notification. You can then handle the payload (if any) and navigate to the desired screen using Navigator.pushNamed
.
Make sure you have set up the desired screen route in your MaterialApp
widget:
MaterialApp(
routes: {
'/desired-screen': (BuildContext context) => DesiredScreen(),
},
// ...
)
That’s it! You should now be able to open a particular screen on clicking on a push notification in your Flutter app.