Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

A comprehensive guide for integrating local notifications in Flutter applications, including setup instructions, code samples, and best practices.

License

NotificationsYou must be signed in to change notification settings

mahmoodhamdi/Flutter-Local-Notifications-Integration-Guide

Repository files navigation

Welcome to theFlutter Local Notifications Integration Guide! This resource is crafted to help developers seamlessly add local notifications to their Flutter applications. Whether you're looking to send alerts, reminders, or messages, this guide provides everything you need—from setup to advanced customization.

📋 Key Features

  • Comprehensive setup instructions for Android and iOS
  • Code examples for both basic and advanced notifications
  • Best practices for notification management and user engagement
  • Troubleshooting tips and common pitfalls to avoid

✨ Features

Implemented Features

  • Display basic notifications
  • Schedule notifications
  • Customize notification appearance (title, body, icon)
  • Cancel all notifications
  • Periodic notifications
  • Custom notification sounds
  • Handle notification taps and responses

Future Enhancements

  • Schedule repeating notifications
  • Group notifications
  • Progress notifications
  • Media style notifications
  • Big picture notifications
  • Inbox style notifications
  • iOS-specific features (attachments, critical alerts)
  • Notification actions and buttons

🚀 Getting Started

Integrating local notifications into your Flutter project is easy! Follow the steps below to get started.

1. Add theflutter_local_notifications Package

Add the package to yourpubspec.yaml file:

dependencies:flutter:sdk:flutterflutter_local_notifications:latest_versiontimezone:latest_version

Install the package by running:

flutter pub get

2. Android Configuration

Add Permissions

Edit yourandroid/app/src/main/AndroidManifest.xml file to include the necessary permissions:

Note: Add these permissions above the<application> tag.

<uses-permissionandroid:name="android.permission.RECEIVE_BOOT_COMPLETED"/><uses-permissionandroid:name="android.permission.SCHEDULE_EXACT_ALARM"/><!-- Other permissions if necessary-->
  • android.permission.RECEIVE_BOOT_COMPLETED: Ensures notifications are rescheduled after device reboot.
  • android.permission.SCHEDULE_EXACT_ALARM: Allows for precise alarm scheduling.

Add Receivers

Insert the following receivers before the end of the<application> tag:

<meta-dataandroid:name="flutterEmbedding"android:value="2" /><receiverandroid:exported="false"android:name="com.dexterous.flutterlocalnotifications.ScheduledNotificationReceiver" /><receiverandroid:exported="false"android:name="com.dexterous.flutterlocalnotifications.ScheduledNotificationBootReceiver">    <intent-filter>        <actionandroid:name="android.intent.action.BOOT_COMPLETED"/>        <actionandroid:name="android.intent.action.MY_PACKAGE_REPLACED"/>        <actionandroid:name="android.intent.action.QUICKBOOT_POWERON"/>        <actionandroid:name="com.htc.intent.action.QUICKBOOT_POWERON"/>    </intent-filter></receiver>

3. Gradle Setup

For scheduled notifications to be compatible with older Android versions, you need to enabledesugaring. Update your application's Gradle fileandroid/app/build.gradle as follows:

android {  defaultConfig {    multiDexEnabledtrue  }  compileOptions {    coreLibraryDesugaringEnabledtrue    sourceCompatibilityJavaVersion.VERSION_1_8    targetCompatibilityJavaVersion.VERSION_1_8  }}dependencies {  coreLibraryDesugaring'com.android.tools:desugar_jdk_libs:1.2.2'}

Make sure your project is usingAndroid Gradle Plugin 7.3.1 or higher.

If your Flutter app crashes on Android 12L or later when desugaring is enabled, you may need to add the following dependencies:

dependencies {    implementation'androidx.window:window:1.0.0'    implementation'androidx.window:window-java:1.0.0'}

Additionally, ensure yourcompileSdk is set to at least 34 in your Gradle configuration:

android {    compileSdk 34}

4. Custom Notification Sound Setup

You can now customize notification sounds with this setup.

Add Sound File

Add your custom notification sound file to the following locations in your project:

  • Flutter assets: Place your sound file inassets/audio/
  • Android raw resources: Add your sound file toandroid/app/src/main/res/raw/

Ensure that the sound file follows these conditions:

  • File format:.mp3
  • File name: Use lowercase letters and underscores (e.g.,yaamsallyallaelnaby.mp3).

Updatepubspec.yaml

Configure the sound asset in yourpubspec.yaml file under theassets section:

flutter:assets:    -assets/audio/

Custom Sound Notification

The custom sound feature is already integrated into the notification helper function. By default, the notification will play the custom sound fileyaamsallyallaelnaby.mp3. You can specify the sound file or let it use the default one as follows:

NotificationHelper.showBasicNotification(  id:Random().nextInt(1<<32),  title:"Custom Sound Notification",  body:"This notification has a custom sound!",  sound:RawResourceAndroidNotificationSound('yaamsallyallaelnaby'),);

If no sound is provided, the default sound (yaamsallyallaelnaby.mp3) will be used.


5. Initialize Notifications and Time Zones

You must initialize the notification plugin along with time zone settings.

Initialization

In yourNotificationHelper, initialize the notification settings and time zones as shown below:

classNotificationHelper {staticfinalFlutterLocalNotificationsPlugin _notification=FlutterLocalNotificationsPlugin();/// Initialize the notification settings and time zones.staticFuture<void>init()async {try {const androidSettings=AndroidInitializationSettings("@mipmap/ic_launcher");const initSettings=InitializationSettings(android: androidSettings);await _notification.initialize(        initSettings,        onDidReceiveBackgroundNotificationResponse: onNotificationTap,        onDidReceiveNotificationResponse: onNotificationTap,      );      tz.initializeTimeZones();    }catch (e) {log("Error initializing notifications: $e");    }  }}

6. Handle Notification Taps

You can now respond to user interactions when they tap on notifications. The tap listener and response handlers are integrated into the notification helper. This allows you to perform actions like navigation when the notification is tapped.

Setup the Notification Tap Listener

Set up a tap listener to perform actions when a user taps on a notification:

classNotificationHelper {staticStreamController<NotificationResponse> notificationResponseController=StreamController<NotificationResponse>.broadcast();/// Add the response to the stream on notification tap.staticvoidonNotificationTap(NotificationResponse notificationResponse,  ) {    notificationResponseController.add(notificationResponse);  }voidonNotificationTapListener() {NotificationHelper.notificationResponseController.stream        .listen((notificationResponse) {Navigator.push(          context,MaterialPageRoute(builder: (context)=>NotificationPage()));    });  }}

Make sure you initialize this listener in yourinitState:

@overridevoidinitState() {super.initState();onNotificationTapListener();// Listen for notification taps}

This will navigate to a specific page when the user taps on the notification.

🎉 Congratulations

You’ve successfully integrated local notifications into your Flutter app! For more advanced features and customization options, be sure to check out the officialFlutter Local Notifications Plugin Documentation.

If you found this guide helpful, don’t forget to ⭐ star this repository on GitHub to show your support!

Thank you for reading!


📝 License

This project is licensed under the MIT License - see theLICENSE file for details.

🤝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

Qoute

مَن قالَ: لا إلَهَ إلَّا اللَّهُ، وحْدَهُ لا شَرِيكَ له، له المُلْكُ وله الحَمْدُ، وهو علَى كُلِّ شَيءٍ قَدِيرٌ، في يَومٍ مِئَةَ مَرَّةٍ؛ كانَتْ له عَدْلَ عَشْرِ رِقابٍ، وكُتِبَتْ له مِئَةُ حَسَنَةٍ، ومُحِيَتْ عنْه مِئَةُ سَيِّئَةٍ، وكانَتْ له حِرْزًا مِنَ الشَّيْطانِ يَومَهُ ذلكَ حتَّى يُمْسِيَ، ولَمْ يَأْتِ أحَدٌ بأَفْضَلَ ممَّا جاءَ به، إلَّا أحَدٌ عَمِلَ أكْثَرَ مِن ذلكَ.

صحيح البخاري

About

A comprehensive guide for integrating local notifications in Flutter applications, including setup instructions, code samples, and best practices.

Topics

Resources

License

Stars

Watchers

Forks


[8]ページ先頭

©2009-2025 Movatter.jp