Flutter Push Notifications Examples
Flutter Push Notifications: How To Examples
Introduction
Push notifications are a crucial feature in modern mobile applications as they allow developers to send timely and relevant updates to users even when the app is not actively running. Flutter, Google's UI toolkit for building natively compiled applications, provides easy integration with push notifications through various plugins and libraries.
In this tutorial, we will explore different scenarios and examples of implementing push notifications in Flutter applications. We will cover everything from installation to handling different types of notifications. So let's get started!
Installation
To begin, make sure you have Flutter and the necessary development environment set up on your machine. Then, follow these steps to install the required plugins for push notifications:
- Open your Flutter project in your preferred IDE.
- Open the
pubspec.yaml
file. - Add the following lines under the
dependencies
section:
dependencies:
firebase_messaging: ^10.0.0
flutter_local_notifications: ^10.2.0
- Save the file and run
flutter pub get
in the terminal to fetch the dependencies.
Example 1: Basic Notification
Let's start with a simple example of displaying a basic push notification in Flutter:
- Import the necessary packages at the beginning of your Dart file:
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
- Initialize the Firebase Messaging and Flutter Local Notifications plugins:
final FirebaseMessaging _firebaseMessaging = FirebaseMessaging.instance;
final FlutterLocalNotificationsPlugin _flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
- Add the following code to request permission for receiving notifications and configure the notification settings:
void requestNotificationPermissions() async {
await _firebaseMessaging.requestPermission();
}
void initializeNotifications() {
const AndroidInitializationSettings initializationSettingsAndroid =
AndroidInitializationSettings('app_icon');
final InitializationSettings initializationSettings =
InitializationSettings(android: initializationSettingsAndroid);
_flutterLocalNotificationsPlugin.initialize(
initializationSettings,
);
}
- Register a callback to handle incoming push notifications:
void registerNotificationCallback() {
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
final notification = message.notification;
final android = message.notification?.android;
if (notification != null && android != null) {
_showNotification(notification.title, notification.body);
}
});
}
- Define the
_showNotification
method to display the notification:
void _showNotification(String title, String body) async {
const AndroidNotificationDetails androidPlatformChannelSpecifics =
AndroidNotificationDetails(
'channel_id',
'channel_name',
'channel_description',
importance: Importance.max,
priority: Priority.high,
);
const NotificationDetails platformChannelSpecifics =
NotificationDetails(android: androidPlatformChannelSpecifics);
await _flutterLocalNotificationsPlugin.show(
0,
title,
body,
platformChannelSpecifics,
);
}
- Finally, call the necessary methods to request permissions, initialize notifications, and register the callback in your Flutter app's lifecycle:
void main() {
runApp(MyApp());
WidgetsBinding.instance?.addPostFrameCallback((_) {
requestNotificationPermissions();
initializeNotifications();
registerNotificationCallback();
});
}
Expected Output: When a push notification is received, the app will display a notification with the given title and body.
Example 2: Custom Notification Actions
In this example, we will extend the previous example to include custom actions in the push notification:
- Modify the
_showNotification
method to include custom actions:
void _showNotification(String title, String body) async {
const AndroidNotificationDetails androidPlatformChannelSpecifics =
AndroidNotificationDetails(
'channel_id',
'channel_name',
'channel_description',
importance: Importance.max,
priority: Priority.high,
actions: [
AndroidNotificationAction(
'action_1',
'Action 1',
),
AndroidNotificationAction(
'action_2',
'Action 2',
),
],
);
const NotificationDetails platformChannelSpecifics =
NotificationDetails(android: androidPlatformChannelSpecifics);
await _flutterLocalNotificationsPlugin.show(
0,
title,
body,
platformChannelSpecifics,
payload: 'custom_payload',
);
}
- Handle the custom actions in the push notification callback:
void registerNotificationCallback() {
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
final notification = message.notification;
final android = message.notification?.android;
final action = message.data['action'];
if (notification != null && android != null) {
if (action == 'action_1') {
// Handle action 1
} else if (action == 'action_2') {
// Handle action 2
} else {
_showNotification(notification.title, notification.body);
}
}
});
}
Expected Output: When a push notification with custom actions is received, the app will display the notification with the given title and body. Tapping on the custom actions will trigger the corresponding action handlers.
Example 3: Scheduled Notifications
In this example, we will demonstrate how to schedule push notifications to be displayed at a specific time:
- Add the following code to schedule a notification:
void scheduleNotification() async {
const AndroidNotificationDetails androidPlatformChannelSpecifics =
AndroidNotificationDetails(
'channel_id',
'channel_name',
'channel_description',
importance: Importance.max,
priority: Priority.high,
);
const NotificationDetails platformChannelSpecifics =
NotificationDetails(android: androidPlatformChannelSpecifics);
await _flutterLocalNotificationsPlugin.zonedSchedule(
0,
'Scheduled Notification',
'This notification was scheduled',
tz.TZDateTime.now(tz.local).add(const Duration(seconds: 5)),
platformChannelSpecifics,
androidAllowWhileIdle: true,
uiLocalNotificationDateInterpretation:
UILocalNotificationDateInterpretation.absoluteTime,
);
}
- Call the
scheduleNotification
method when desired, for example, in a button'sonPressed
callback.
Expected Output: The app will schedule a push notification to be displayed 5 seconds after the scheduling code is triggered.
Example 4: Background Notifications
In this example, we will handle push notifications even when the app is running in the background or terminated:
- Add the following code to the
registerNotificationCallback
method:
void registerNotificationCallback() {
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
// Handle the notification when the app is open
});
FirebaseMessaging.onBackgroundMessage((RemoteMessage message) async {
// Handle the notification when the app is in the background or terminated
_showNotification(message.notification?.title, message.notification?.body);
});
}
- Ensure you have the necessary configurations in your Android and iOS project files to handle background notifications. Refer to the official documentation for detailed instructions on setting up background notifications.
Expected Output: When a push notification is received while the app is in the background or terminated, the app will display the notification and handle it accordingly.
Conclusion
In this tutorial, we explored various examples of implementing push notifications in Flutter applications. We covered the basics of displaying notifications, adding custom actions, scheduling notifications, and handling background notifications. By following these examples, you can enhance your Flutter apps with push notification functionality.