How To Set Up Local Notifications in Flutter Framework
Notifications have become an integral part of smartphone users, it works as an alert system to inform users of updates, offers, and the latest trends so that they never miss out on their favorite deals. But what is the entire purpose of notifications? As a business, it helps in catching the eyes of the users from time to time while engaging them for a better user experience.
When an application is in the development phase, a mobile app development company keeps in check a few of the mandatory features of which notifications are also a part. There are two types of notifications– Push Notifications and Local Notifications.
Push notifications are alerts that a program generates when it is not open, usually in the form of a pop-up or other message, informing the user of a new message, update, social network post, etc.
Whereas, notifications that your app schedules and shows on the user’s device on its own are known as Local notifications. They are great for creating reminders or starting events depending on the user’s behavior and don’t require internet access.
Through this guide, you will be able to implement Local Notifications in Flutter for both iOS & Android platforms.
Why Flutter? Because it is the framework that has come from zero to hero!
Here’s what we are going to learn:
- Setting up the Flutter project
- Configuring local notifications
- Implementing local notification features
- Testing the implementation
- Advanced topic and best practices
Before we kickstart the setting up of the project if you are a startup business in the USA you must read our top 7 Flutter development service providers. Why because without their assistance how will you set up a project?
Setting Up Your Flutter Project
We’ll walk you through the process of integrating local notifications into a Flutter app in this section. Make sure you have installed Flutter on your machine before continuing. If not, install Flutter using the official instructions found here.
1. Creating a new flutter project
In your terminal or command prompt, use the following command to start a new Flutter project if you haven’t already:
flutter create my_notification_app
Change my_notification_app to the project name you like.
2. Include Necessary Dependencies
You must add the required dependencies to your Flutter project to enable local notifications. The flutter_local_notifications package, which offers a straightforward API for handling local notifications, will be used in this tutorial.
Open the pubspec.yaml file for your project and add the following dependency:
1 2 3 4 5 6 7 |
dependencies: flutter: sdk: flutter flutter_local_notifications: ^5.0.0+4 |
After adding the dependency, save the file and run the following command to install the packages:
flutter pub get
Go through our top 10 Flutter packages to speed up the app development.
3. Platform-Dependent Config
For both Android and iOS app development services, platform-specific customizations are needed for local notifications. Let’s go over what has to be done on each platform.
Android Configuration
Open the AndroidManifest.xml file for Android by going to the android/app/src/main directory. Include the following settings and permissions in the <manifest> tag:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.my_notification_app"> <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/> <application ... <receiver android:name="com.dexterous.flutterlocalnotifications.ScheduledNotificationBootReceiver"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED"/> <action android:name="android.intent.action.MY_PACKAGE_REPLACED"/> </intent-filter> </receiver> <receiver android:name="com.dexterous.flutterlocalnotifications.ScheduledNotificationReceiver"/> </application> </manifest> |
iOS Setup
For iOS, open the Info.plist file located in ios/Runner directory. Add the following key-value pair to request permissions for displaying notifications:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<key>NSAppTransportSecurity</key> <dict> <key>NSAllowsArbitraryLoads</key> <true/> </dict> <key>UIBackgroundModes</key> <array> <string>fetch</string> <string>notification</string> </array> |
Now that the platform configurations and dependencies are in place, your Flutter app is ready to add local notifications. In the following section, we will go over setting up and implementing local notifications in your Flutter app.
Configuring Local Notifications:
1. Initializing Local Notifications
Let’s start by initializing the local notifications plugin in your Flutter app development services project. Open the main.dart file in your projects lib directory. Add the below-mentioned code to start the initializing the local notifications plugin process:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
import 'package:flutter/material.dart'; import 'package:flutter_local_notifications/flutter_local_notifications.dart'; final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin(); void main() async { WidgetsFlutterBinding.ensureInitialized(); final InitializationSettings initializationSettings = InitializationSettings( android: AndroidInitializationSettings('@mipmap/ic_launcher'), iOS: IOSInitializationSettings(), ); await flutterLocalNotificationsPlugin.initialize(initializationSettings, onSelectNotification: onSelectNotification); runApp(MyApp()); } Future<void> onSelectNotification(String? payload) async { // Handle notification click event } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Local Notifications Demo', home: MyHomePage(), ); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
class MyHomePage extends StatefulWidget { @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Local Notifications Demo'), ), body: Center( child: Text('Welcome to Local Notifications Demo!'), ), ); } } |
In this code snippet:
- We import the necessary packages and initialize the ‘FlutterLocalNotificationsPlugin’ instance.
- We make sure Flutter is initialized and set up the local notifications plugin with the necessary parameters in the main() method.
- To handle notification click events, we construct a placeholder method called onSelectNotification().
- We build a basic Flutter application with a welcome message on the home screen.
2. Tailoring Notification Actions
By adjusting parameters like channel settings, notification look, and default behaviors, you may alter how local notifications behave. After initializing the plugin, open the main.dart file and add the following code to the main() function:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
final AndroidInitializationSettings initializationSettingsAndroid = AndroidInitializationSettings('@mipmap/ic_launcher'); final IOSInitializationSettings initializationSettingsIOS = IOSInitializationSettings(); final InitializationSettings initializationSettings = InitializationSettings( android: initializationSettingsAndroid, iOS: initializationSettingsIOS); await flutterLocalNotificationsPlugin.initialize(initializationSettings, onSelectNotification: onSelectNotification); // Define Android-specific notification channel settings const AndroidNotificationChannel channel = AndroidNotificationChannel( 'default_notification_channel', 'Default Notification Channel', 'This channel is used for important notifications', importance: Importance.high, playSound: true, ); await flutterLocalNotificationsPlugin .resolvePlatformSpecificImplementation< AndroidFlutterLocalNotificationsPlugin>() ?.createNotificationChannel(channel); |
In this code snippet:
- We define platform-specific initialization settings for Android & iOS.
- We create an Android notification channel with specified settings like channel ID, name, description, importance level, and whether to play sound.
Great! Now that you have configured local notifications in your Flutter project, it’s time to implement local notifications, including scheduling and displaying notifications to the user.
Implementing Local Notifications Features in Flutter Framework
From creating, scheduling, and displaying, we are going to implement local notifications in Flutter in this section.
1. Creating and Scheduling Notifications
Usually, you’ll use the flutterLocalNotificationsPlugin.show() function with the necessary arguments to generate and schedule notifications. To schedule a notice, open your preferred file (main.dart, for example) and add the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 |
import 'package:flutter/material.dart'; import 'package:flutter_local_notifications/flutter_local_notifications.dart'; final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin(); void main() async { WidgetsFlutterBinding.ensureInitialized(); final InitializationSettings initializationSettings = InitializationSettings( android: AndroidInitializationSettings('@mipmap/ic_launcher'), iOS: IOSInitializationSettings(), ); await flutterLocalNotificationsPlugin.initialize(initializationSettings, onSelectNotification: onSelectNotification); // Schedule a notification await _scheduleNotification(); runApp(MyApp()); } Future<void> onSelectNotification(String? payload) async { // Handle notification click event } Future<void> _scheduleNotification() async { const AndroidNotificationDetails androidPlatformChannelSpecifics = AndroidNotificationDetails( 'scheduled_channel', 'Scheduled notifications', 'Scheduled notifications channel', ); const IOSNotificationDetails iOSPlatformChannelSpecifics = IOSNotificationDetails(); const NotificationDetails platformChannelSpecifics = NotificationDetails( android: androidPlatformChannelSpecifics, iOS: iOSPlatformChannelSpecifics); await flutterLocalNotificationsPlugin.zonedSchedule( 0, 'Scheduled Title', 'Scheduled Body', DateTime.now().add(const Duration(seconds: 5)), platformChannelSpecifics, androidAllowWhileIdle: true, uiLocalNotificationDateInterpretation: UILocalNotificationDateInterpretation.absoluteTime, matchDateTimeComponents: DateTimeComponents.time, ); } |
In this snippet code:
- To plan a notice to appear after five seconds, we define the method _scheduleNotification().
- For iOS and Android, we specify platform-specific notification information.
- To schedule the notification, we use the flutterLocalNotificationsPlugin.zonedSchedule() function.
2. Managing Notification Select Events.
You may write a function and give it as the onSelectNotification callback during startup to handle notification click events. Open the file you choose, such as main.dart, and add the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
Future<void> onSelectNotification(String? payload) async { // Handle notification click event showDialog( context: context, builder: (_) => AlertDialog( title: Text('Notification Clicked'), content: Text('Notification Clicked with payload: $payload'), ), ); } |
In this code snippet:
- To display an AlertDialog when the notification is clicked, we define the onSelectNotification() method.
- Any further information related to the notice is contained in the payload parameter.
Wait there’s more to creating your local notification in Flutter beyond what we’ve covered so far.
Additional Aspects You Must Know About Local Notifications in Flutter:
Customizing Notification Appearance:
You can alter the notification’s icon, tone, vibration, priority, and other visual elements. For platform-specific parameters, this may be accomplished using the AndroidNotificationDetails and IOSNotificationDetails classes.
Managing Notification Payloads:
You may add extra information (payload) to your alerts. This information might help set the scene or cause the user to do particular actions when they engage with the notice.
Managing Scheduled Notifications:
In addition to setting up alerts for instantaneous display, you may program alerts to appear at particular future dates and times, or even recurrently at predetermined intervals.
Managing Notification Channels (Android):
To improve control over the behavior of notifications, Android mandates that they be assigned to notification channels. The AndroidNotificationChannel class is used to establish and manage notification channels.
Foreground Service (Android):
To guarantee that alerts are presented properly, you may need to employ foreground services for specific sorts of notifications, such as those related to ongoing activities or background processes.
Plugins for Local Notifications:
Although the flutter_local_notifications plugin was utilized in this instance, there are alternative plugins that may manage local notifications inside Flutter. You may discover that another plugin is more appropriate, depending on your particular needs.
These additional aspects contribute to a comprehensive and robust local notification implementation in your Flutter app development services. Depending on your app’s requirements and complexity, you may need to delve deeper into these areas to ensure a seamless user experience.
Testing Your Local Notifications in Flutter Implementation
We’ll go over a few different methods in this section for testing your Flutter project’s local notification solution. Testing ensures that alerts appear correctly and operate as you intended when users engage with your app.
1. Examining Using Simulators and Emulators
Using emulators or simulators to test your Flutter app’s local notification implementation is the simplest method. This lets you play out various situations, such as getting notifications whether the app is running in the background or the forefront.
To try using an emulator for Android:
flutter emulators –launch <emulator_id>
flutter run
To test on iOS simulator:
open -a Simulator
flutter run
2. Manual Testing
Manual testing of your app entails setting off several notification kinds and seeing how they behave. This covers managing several interaction scenarios, such as touching on the notice or dismissing it, as well as testing scheduled notifications and notifications with payloads.
3. Troubleshooting
Debugging techniques are essential for identifying and resolving any issues that may develop during the testing of your local notification solution. Examine the flow of your notification processing code using print statements or debugging tools from Flutter (like the Flutter DevTools) to find any mistakes or strange behaviour.
4. Computerized Examination
To ensure that your implementation of local notifications is working properly, think about putting automated tests in place. With the help of Flutter, you can test your app’s intended functionality, including local notifications, by simulating user interactions and using tools like widgets and integration tests.
An example of a widget test to confirm notification display:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
testWidgets('Notification should be displayed', (WidgetTester tester) async { // Build your widget await tester.pumpWidget(MyApp()); // Trigger notification await _scheduleNotification(); // Verify notification is displayed expect(find.text('Scheduled Body'), findsOneWidget); }); |
5. Examining Using Real Devices
Even while emulators and simulators offer a practical testing environment, you must also test your app on actual hardware. This makes it easier to guarantee that your program will function properly on a variety of device configurations, including those with varying screen sizes, hardware specs, and operating systems.
Local Notifications in Flutter Advanced Topics & Best Practices
Grouping Notifications:
One helpful approach for displaying the user with several alerts in a logical order is to group the notifications. This keeps the notification tray clear of clutter and facilitates notification management for users.
When creating notifications using the display() function, you may use the groupKey option to group messages. This enables alerts in the notification tray to be grouped based on their groupKey.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
flutterLocalNotificationsPlugin.show( 0, 'Notification Title', 'Notification Body', platformChannelSpecifics, payload: 'New Notification', groupKey: 'group_key', ); |
Handling Notification Interactions:
To increase user engagement, provide consumers with interactive alternatives right from the notice. To enable users to take action without opening the app, you may include actions in your alerts, such “Open,” “Dismiss,” and “Reply.”
When generating notifications using the display() function, take advantage of the actions argument to add actions to your alerts.
Customizing Notification Appearance:
Adapt the look of your alerts to the style and branding of your app. Aspects of the notification that you may alter include the vibration pattern, tone, color, and icon.
The AndroidNotificationDetails class on Android and the iOSNotificationDetails class on iOS are used to change the look of notifications, respectively.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
const AndroidNotificationDetails androidPlatformChannelSpecifics = AndroidNotificationDetails( 'your_channel_id', 'your_channel_name', 'your_channel_description', importance: Importance.max, priority: Priority.high, enableVibration: true, vibrationPattern: Int64List.fromList([0, 1000, 500, 1000]), playSound: true, sound: RawResourceAndroidNotificationSound('notification_sound'), styleInformation: DefaultStyleInformation(true, true), ); const IOSNotificationDetails iOSPlatformChannelSpecifics = IOSNotificationDetails( sound: 'notification_sound.aiff', ); const NotificationDetails platformChannelSpecifics = NotificationDetails( android: androidPlatformChannelSpecifics, iOS: iOSPlatformChannelSpecifics, ); |
Optimize Battery And Performance:
Consider how local notifications affect the functionality and battery life of your smartphone. Steer clear of setting too many alerts or using them excessively since this may severely affect performance and deplete the device’s battery.
To reduce the quantity of alerts that are provided to the user, think about employing batch processing or merging messages where necessary.
Handle Edge Cases:
Be prepared for and gently handle edge circumstances including app upgrades, device reboots, and unsuccessful notification delivery. To guarantee continuous notification delivery, use logic to reschedule missed alerts during device outages or change the notification settings when an app is updated.
There are a few Flutter app best practices that streamline a business workflow, want to know? Give the blog a read!
That’s a Wrap
In this comprehensive guide, we’ve covered everything you need to know about setting up and implementing local notifications in your Flutter app.
From configuring your project and scheduling notifications to handling interactions and optimizing performance, we’ve provided step-by-step instructions and best practices to ensure seamless integration.
However, if you find yourself needing expert assistance or want to expedite the process, consider hiring a Flutter app development company. With their expertise and experience, they can help you set up local notifications efficiently and effectively, ensuring that your app delivers timely and engaging notifications to users.
Why hire Flutter developers from DianApps in 2024? Get the all details here!
Don’t wait any longer—hire a dedicated app developer from us today to take your app’s notification system to the next level!