flutter - Notification not displayed - flutter

I am trying to display local notifications. I do not understand what I am missing, but the notification does not displayed. I have tried with the application active. But it works when the app is in the background.
I have checked the configuration and notifications are allowed. If you can help it would be great. Thank you.
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:rxdart/rxdart.dart';
import 'package:timezone/data/latest.dart' as tz;
import 'package:timezone/timezone.dart' as tz;
import 'package:flutter_native_timezone/flutter_native_timezone.dart';
class NotificationApi {
static final _notifications = FlutterLocalNotificationsPlugin();
static final onNotifications = BehaviorSubject<String?>();
static Future _notificationDetails() async {
/*final largeIconPath = await Utils.downloadFile(
'https://images.unsplash.com/photo-1597223557154-721c1cecc4b0?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=80',
'largeIcon',
);*/
/*final bigPicturePath = await Utils.downloadFile(
'https://images.unsplash.com/photo-1589010588553-46e8e7c21788?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=400&q=80',
'bigPicture',
);*/
// final styleInformation = BigPictureStyleInformation(
// FilePathAndroidBitmap(bigPicturePath),
// largeIcon: FilePathAndroidBitmap(largeIconPath),
// );
/// Download: https://samplefocus.com/samples/chime-notification-alert
const sound = 'notification_sound.wav';
return NotificationDetails(
android: AndroidNotificationDetails(
'channel id 8',
'channel name',
channelDescription: 'channel description',
importance: Importance.max,
//playSound: false,
sound: RawResourceAndroidNotificationSound(sound.split('.').first),
enableVibration: false,
// styleInformation: styleInformation,
),
iOS: const IOSNotificationDetails(
presentSound: false,
sound: sound,
),
);
}
static Future init({bool initScheduled = false}) async {
const android = AndroidInitializationSettings('#mipmap/ic_launcher');
const iOS = IOSInitializationSettings();
const settings = InitializationSettings(android: android, iOS: iOS);
/// Handle payload when app is closed
final details = await _notifications.getNotificationAppLaunchDetails();
if (details != null && details.didNotificationLaunchApp) {
onNotifications.add(details.payload);
}
await _notifications.initialize(
settings,
onSelectNotification: (payload) async {
onNotifications.add(payload);
},
);
if (initScheduled) {
tz.initializeTimeZones();
final locationName = await FlutterNativeTimezone.getLocalTimezone();
tz.setLocalLocation(tz.getLocation(locationName));
}
}
/// Direct Notification
static Future showNotification({
int id = 0,
String? title,
String? body,
String? payload,
}) async =>
_notifications.show(
id,
title,
body,
await _notificationDetails(),
payload: payload,
);
/// Notification for specific DateTime
static void showScheduledNotification({
int id = 0,
String? title,
String? body,
String? payload,
required DateTime scheduledDate,
}) async =>
_notifications.zonedSchedule(
id,
title,
body,
tz.TZDateTime.from(scheduledDate, tz.local),
await _notificationDetails(),
payload: payload,
androidAllowWhileIdle: true,
uiLocalNotificationDateInterpretation:
UILocalNotificationDateInterpretation.absoluteTime,
);
static tz.TZDateTime _scheduleDaily(Time time) {
final now = tz.TZDateTime.now(tz.local);
final scheduledDate = tz.TZDateTime(tz.local, now.year, now.month, now.day,
time.hour, time.minute, time.second);
return scheduledDate.isBefore(now)
? scheduledDate.add(const Duration(days: 1))
: scheduledDate;
}
static List<tz.TZDateTime> _scheduleWeekly(Time time,
{required List<int> days}) {
return days.map((day) {
tz.TZDateTime scheduledDate = _scheduleDaily(time);
while (day != scheduledDate.weekday) {
scheduledDate = scheduledDate.add(const Duration(days: 1));
}
return scheduledDate;
}).toList();
}
static void cancel(int id) => _notifications.cancel(id);
static void cancelAll() => _notifications.cancelAll();
}
#override
void initState() {
super.initState();
_contextSelected = _context;
NotificationApi.init();
listenNotifications();
}
void onClickedNotification(String? payload) {
// Navigator.of(context).push(MaterialPageRoute(
// builder: (context) => SecondPage(payload: payload),
// ));
} //TODO a modifier pour que envoie sur bonne page view detail task
void listenNotifications() =>
NotificationApi.onNotifications.stream.listen(onClickedNotification);
then, I have a button, on Tap, I want this code below to be executed
NotificationApi.showScheduledNotification(
title: 'Test notification',
body: 'Today at 6 PM',
payload: 'test_notification_6pm',
scheduledDate: DateTime.now().add(const Duration(seconds: 4)),
);

Try adding this
static Future<void> _configureLocalTimeZone() async {
tz.initializeTimeZones();
final String timeZone = await FlutterNativeTimezone.getLocalTimezone();
tz.setLocalLocation(tz.getLocation(timeZone));
}
method and call it at the top of the init() method of your NotificationAPI class.

Related

The argument type 'Future<void> Function(String?)' can't be assigned to the parameter type 'void Function(NotificationResponse)?

I'm trying to include local notifications in my Flutter project using the latest version flutter_local_notifications: ^13.0.0, and I have this error:
The argument type 'Future Function(String?)' can't be assigned to the parameter type 'void Function(NotificationResponse)?
onDidReceiveNotificationResponse : onSelectNotification
This is my class:
class LocalNotificationService {
LocalNotificationService();
final _localNotificationService = FlutterLocalNotificationsPlugin();
final BehaviorSubject<String?> onNotificationClick = BehaviorSubject();
Future<void> initialize() async {
tz.initializeTimeZones();
const AndroidInitializationSettings androidInitializationSettings =
AndroidInitializationSettings('#drawable/ic_stat_android');
DarwinInitializationSettings iosInitializationSettings =
DarwinInitializationSettings(
requestAlertPermission: true,
requestBadgePermission: true,
requestSoundPermission: true,
onDidReceiveLocalNotification: onDidReceiveLocalNotification,
);
final InitializationSettings settings = InitializationSettings(
android: androidInitializationSettings,
iOS: iosInitializationSettings,
);
await _localNotificationService.initialize(
settings,
onDidReceiveNotificationResponse : onSelectNotification, //here is the error
);
}
Future<NotificationDetails> _notificationDetails() async {
const AndroidNotificationDetails androidNotificationDetails =
AndroidNotificationDetails('channel_id', 'channel_name',
channelDescription: 'description',
importance: Importance.max,
priority: Priority.max,
playSound: true);
const DarwinNotificationDetails iosNotificationDetails =
DarwinNotificationDetails();
return const NotificationDetails(
android: androidNotificationDetails,
iOS: iosNotificationDetails,
);
}
Future<void> showNotification({
required int id,
required String title,
required String body,
}) async {
final details = await _notificationDetails();
await _localNotificationService.show(id, title, body, details);
}
Future<void> showScheduledNotification(
{required int id,
required String title,
required String body,
required int seconds}) async {
final details = await _notificationDetails();
await _localNotificationService.zonedSchedule(
id,
title,
body,
tz.TZDateTime.from(
DateTime.now().add(Duration(seconds: seconds)),
tz.local,
),
details,
androidAllowWhileIdle: true,
uiLocalNotificationDateInterpretation:
UILocalNotificationDateInterpretation.absoluteTime,
);
}
Future<void> showNotificationWithPayload(
{required int id,
required String title,
required String body,
required String payload}) async {
final details = await _notificationDetails();
await _localNotificationService.show(id, title, body, details,
payload: payload);
}
void onDidReceiveLocalNotification(
int id, String? title, String? body, String? payload) {
print('id $id');
}
Future<void> onSelectNotification(String? payload) async {
print('payload $payload');
if (payload != null && payload.isNotEmpty) {
onNotificationClick.add(payload);
}
}
}
What I'm missing?
onDidReceiveNotificationResponse provide NotificationResponse on callback. You can get payload like
onDidReceiveNotificationResponse: (details) =>
onSelectNotification(details.payload),
Or
Future<void> onSelectNotification(NotificationResponse? response) async {
print('payload $response');
if (response?.payload != null && response!.payload!.isNotEmpty) {
onNotificationClick.add(response.payload);
}
}
And this will be used onDidReceiveNotificationResponse : onSelectNotification.

Flutter - errors after an update - notifications

I have updated the pods in my app. And now I have some errors. I have been able to fix few of them, but I still have two where I do not find what I should do. Please, can you help? Thank you.
I am using flutter_local_notifications: ^10.0.0
The other errors have been fixed. I guess that I should not have updated the files, but my objective was to fix a buffer overflow problem.
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:rxdart/rxdart.dart';
import 'package:timezone/data/latest.dart' as tz;
import 'package:timezone/timezone.dart' as tz;
import 'package:flutter_native_timezone/flutter_native_timezone.dart';
class NotificationApi {
static final _notifications = FlutterLocalNotificationsPlugin();
static final onNotifications = BehaviorSubject<String?>();
static Future _notificationDetails() async {
const sound = 'notification_sound.wav';
return NotificationDetails(
android: AndroidNotificationDetails(
'channel id 8',
'channel name',
channelDescription: 'channel description',
importance: Importance.max,
//playSound: false,
sound: RawResourceAndroidNotificationSound(sound.split('.').first),
enableVibration: false,
// styleInformation: styleInformation,
),
iOS: const DarwinNotificationDetails(
presentSound: false,
sound: sound,
),
);
}
static Future init({bool initScheduled = false}) async {
const android = AndroidInitializationSettings('#mipmap/ic_launcher');
const iOS = DarwinInitializationSettings();
const settings = InitializationSettings(android: android, iOS: iOS);
/// Handle payload when app is closed
final details = await _notifications.getNotificationAppLaunchDetails();
if (details != null && details.didNotificationLaunchApp) {
onNotifications.add(details.payload); ///ERROR (The named parameter 'onSelectNotification' isn't defined.)
}
await _notifications.initialize(
settings,
onSelectNotification: (payload) async {
onNotifications.add(payload); ///ERROR (The getter 'payload' isn't defined for the type 'NotificationAppLaunchDetails'.)
},
);
if (initScheduled) {
tz.initializeTimeZones();
final locationName = await FlutterNativeTimezone.getLocalTimezone();
tz.setLocalLocation(tz.getLocation(locationName));
}
}
/// Direct Notification
static Future showNotification({
int id = 0,
String? title,
String? body,
String? payload,
}) async =>
_notifications.show(
id,
title,
body,
await _notificationDetails(),
payload: payload,
);
/// Notification for specific DateTime
static void showScheduledNotification({
int? id ,
String? title,
String? body,
String? payload,
required DateTime scheduledDate,
}) async =>
_notifications.zonedSchedule(
id!,
title,
body,
tz.TZDateTime.from(scheduledDate, tz.local),
await _notificationDetails(),
payload: payload,
androidAllowWhileIdle: true,
uiLocalNotificationDateInterpretation:
UILocalNotificationDateInterpretation.absoluteTime,
);
static tz.TZDateTime _scheduleDaily(Time time) {
final now = tz.TZDateTime.now(tz.local);
final scheduledDate = tz.TZDateTime(tz.local, now.year, now.month, now.day,
time.hour, time.minute, time.second);
return scheduledDate.isBefore(now)
? scheduledDate.add(const Duration(days: 1))
: scheduledDate;
}
static List<tz.TZDateTime> _scheduleWeekly(Time time,
{required List<int> days}) {
return days.map((day) {
tz.TZDateTime scheduledDate = _scheduleDaily(time);
while (day != scheduledDate.weekday) {
scheduledDate = scheduledDate.add(const Duration(days: 1));
}
return scheduledDate;
}).toList();
}
static void cancel(int id) => _notifications.cancel(id);
static void cancelAll() => _notifications.cancelAll();
static int convertStringToHash (String id) {
int notificationId = id.hashCode;
return notificationId;
}
}

Flutter local notifications daily scheduled notification

I've been trying to get Flutter local notifications to work since a week but can't get it to work.
Basically the issue is whenever i create a daily notification, it works only for the first time and then it doesn't show notifications every next day.
Suppose if i set daily scheduled notification at 12:20 PM, it will show notification at 12:20 PM for first time, then the next day it won't show. And when i see the list of pending notifications i can see the notification still present.
here's all my notification code
class NotificationService {
// Singleton pattern
static final NotificationService _notificationService =
NotificationService._internal();
factory NotificationService() {
return _notificationService;
}
NotificationService._internal();
static const channelId = "1";
final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
static const AndroidNotificationDetails _androidNotificationDetails =
AndroidNotificationDetails(
channelId,
"thecodexhub",
channelDescription:
"This channel is responsible for all the local notifications",
playSound: true,
priority: Priority.high,
importance: Importance.high,
);
static const IOSNotificationDetails _iOSNotificationDetails =
IOSNotificationDetails();
final NotificationDetails notificationDetails = const NotificationDetails(
android: _androidNotificationDetails,
iOS: _iOSNotificationDetails,
);
Future<void> init() async {
const AndroidInitializationSettings androidInitializationSettings =
AndroidInitializationSettings('#mipmap/ic_launcher');
const IOSInitializationSettings iOSInitializationSettings =
IOSInitializationSettings(
defaultPresentAlert: false,
defaultPresentBadge: false,
defaultPresentSound: false,
);
const InitializationSettings initializationSettings =
InitializationSettings(
android: androidInitializationSettings,
iOS: iOSInitializationSettings,
);
// *** Initialize timezone here ***
tz.initializeTimeZones();
await flutterLocalNotificationsPlugin.initialize(
initializationSettings,
onSelectNotification: onSelectNotification,
);
}
Future<void> requestIOSPermissions() async {
await flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<
IOSFlutterLocalNotificationsPlugin>()
?.requestPermissions(
alert: true,
badge: true,
sound: true,
);
}
Future<void> showNotification(
int id, String title, String body, String payload) async {
await flutterLocalNotificationsPlugin.show(
id,
title,
body,
notificationDetails,
payload: payload,
);
}
Future<void> scheduleNotification(int id, String title, String body,
DateTime eventDate, TimeOfDay eventTime, String payload,
[DateTimeComponents? dateTimeComponents]) async {
final scheduledTime = eventDate.add(Duration(
hours: eventTime.hour,
minutes: eventTime.minute,
));
await flutterLocalNotificationsPlugin.zonedSchedule(
id,
title,
body,
tz.TZDateTime.from(scheduledTime, tz.local),
notificationDetails,
uiLocalNotificationDateInterpretation:
UILocalNotificationDateInterpretation.absoluteTime,
androidAllowWhileIdle: true,
payload: payload,
matchDateTimeComponents: dateTimeComponents,
);
}
Future<void> cancelNotification(int id) async {
await flutterLocalNotificationsPlugin.cancel(id);
}
Future<void> cancelAllNotifications() async {
await flutterLocalNotificationsPlugin.cancelAll();
}
Future getNotifications() async {
final List<PendingNotificationRequest> pendingNotificationRequests =
await FlutterLocalNotificationsPlugin().pendingNotificationRequests();
return pendingNotificationRequests;
}
}
Future<void> onSelectNotification(String? payload) async {
// await navigatorKey.currentState
// ?.push(MaterialPageRoute(builder: (_) => DetailsPage(payload: payload)));
}
and here's how i'm calling it.
await notificationService.scheduleNotification(
1,
_textEditingController.text,
"Reminder for your scheduled event at ${eventTime!.format(context)}",
eventDate!,
eventTime!,
jsonEncode({
"title": _textEditingController.text,
"eventDate": DateFormat("EEEE, d MMM y").format(eventDate!),
"eventTime": eventTime!.format(context),
}),
getDateTimeComponents(),
);
}
here is getDateTimeComponents if it matters
DateTimeComponents? getDateTimeComponents() {
if (segmentedControlGroupValue == 1) {
return DateTimeComponents.time;
} else if (segmentedControlGroupValue == 2) {
return DateTimeComponents.dayOfWeekAndTime;
}
}
it's been week since i'm trying to fix this issue.
Thank you for reading.
Here it says
Use zonedSchedule instead by passing a date in the future with the
same time and pass DateTimeComponents.matchTime as the value of the
matchDateTimeComponents parameter.
You seem to use DateTimeComponents.time correctly but I guess your date is not in the future. Can you try adding like a thousand years to your date and see? Maybe because after the first firing, the date is now in the past and it will not fire on the next day because of it.

Flutter Local Notification not working in background?

I am using flutter local notification to display schedule notification in my app. But unfortunately it is not working when app is in terminated state.
Here is my code:
class Notifications {
static final FlutterLocalNotificationsPlugin _notifications =
FlutterLocalNotificationsPlugin();
static Future<NotificationDetails> _notificationDetails() async {
return const NotificationDetails(
android: AndroidNotificationDetails(
'weekly notification channel id',
'weekly notification channel name',
channelDescription: 'weekly notification description',
playSound: true,
sound: RawResourceAndroidNotificationSound('azan1'),
importance: Importance.high,
),
iOS: IOSNotificationDetails(sound: 'azan1.mp3', presentSound: true));
}
static void init() async {
tz.initializeTimeZones();
const AndroidInitializationSettings android =
AndroidInitializationSettings('#mipmap/ic_launcher');
const IOSInitializationSettings iOS = IOSInitializationSettings();
InitializationSettings settings =
const InitializationSettings(android: android, iOS: iOS);
await _notifications.initialize(settings);
final String locationName = await FlutterNativeTimezone.getLocalTimezone();
tz.setLocalLocation(tz.getLocation(locationName));
}
static void showScheduledNotification(
int id, {
required DateTime scheduledDate,
String? title,
String? body,
String? payload,
}) async {
await _notifications.zonedSchedule(
id,
'Azan Time',
'$body Prayer Time',
_scheduleDaily(
Time(scheduledDate.hour, scheduledDate.minute, scheduledDate.second)),
await _notificationDetails(),
androidAllowWhileIdle: true,
uiLocalNotificationDateInterpretation:
UILocalNotificationDateInterpretation.absoluteTime,
matchDateTimeComponents: DateTimeComponents.time,
payload: payload,
);
}
static tz.TZDateTime _scheduleDaily(Time time) {
tz.TZDateTime now = tz.TZDateTime.now(tz.local);
tz.TZDateTime schdeuledDate = tz.TZDateTime(tz.local, now.year, now.month,
now.day, time.hour, time.minute, time.second);
return schdeuledDate.isBefore(now)
? schdeuledDate.add(const Duration(days:1))
: schdeuledDate;
}
static Future<void> cancelNotification(int id) async {
await _notifications.cancel(id);
}
static Future<void> cancelAllNotifications() async {
await _notifications.cancelAll();
}
}
I have also added all properties in Android.xml file.
But still it is not working if anybody know the solution of this problem kindly answer this question.
In your Application.java if this part not work you can escape it to run the app .
private void createNotificationChannels() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channelHigh = new NotificationChannel(
CHANNEL_HIGH,
"Notificación Importante",
NotificationManager.IMPORTANCE_HIGH
);
channelHigh.setDescription("Canal Alto");
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(channelHigh);
}
}
Check the Manifest File and do not forget to add
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="default"/>
For More Check This Link
Local notifications might be a bit tricky. Look at the flutter_local_notifications README file:
Some Android OEMs have their own customised Android OS that can prevent applications from running in the background. Consequently, scheduled notifications may not work when the application is in the background on certain devices (e.g. by Xiaomi, Huawei). If you experience problems like this then this would be the reason why. As it's a restriction imposed by the OS, this is not something that can be resolved by the plugin. Some devices may have setting that lets users control which applications run in the background. The steps for these can vary but it is still up to the users of your application to do given it's a setting on the phone itself.
It has been reported that Samsung's implementation of Android has imposed a maximum of 500 alarms that can be scheduled via the Alarm Manager API and exceptions can occur when going over the limit.
Source:
https://pub.dev/packages/flutter_local_notifications#scheduled-android-notifications
If you could provide your main function, it would have been helpful. I'll give you a general example of how to create any scheduled notification.
import 'package:flutter_native_timezone/flutter_native_timezone.dart';
import 'package:rxdart/rxdart.dart';
import 'package:timezone/data/latest.dart' as tz;
import 'package:timezone/timezone.dart' as tz;
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
class NotificationApi {
static final _notification = FlutterLocalNotificationsPlugin();
static final onNotifications = BehaviorSubject<String?>();
static Future _notificationDetails() async {
return const NotificationDetails(
android: AndroidNotificationDetails(
'channel id',
'channel name',
channelDescription: 'Update users on new deal',
importance: Importance.max,
enableLights: true,
),
iOS: IOSNotificationDetails(),
);
}
static Future init({bool initScheduled = true}) async {
const android = AndroidInitializationSettings('#drawable/ic_notcion');
const iOS = IOSInitializationSettings();
const settings = InitializationSettings(android: android, iOS: iOS);
/// when app is closed
final details = await _notification.getNotificationAppLaunchDetails();
if (details != null && details.didNotificationLaunchApp) {
onNotifications.add(details.payload);
}
await _notification.initialize(
settings,
onSelectNotification: (payload) async {
onNotifications.add(payload);
},
);
if(initScheduled){
tz.initializeTimeZones();
final locationName = await FlutterNativeTimezone.getLocalTimezone();
tz.setLocalLocation(tz.getLocation(locationName));
}
}
static tz.TZDateTime _scheduledDaily(Time time) {
final now = tz.TZDateTime.now(tz.local);
final scheduledDate = tz.TZDateTime(tz.local, now.year, now.month, now.day,
time.hour);
return scheduledDate.isBefore(now)
? scheduledDate.add(const Duration(days: 1))
: scheduledDate;
}
static tz.TZDateTime _scheduleWeekly(Time time, {required List<int> days}) {
tz.TZDateTime scheduledDate = _scheduledDaily(time);
while (!days.contains(scheduledDate.weekday)) {
scheduledDate = scheduledDate.add(const Duration(days: 1));
}
return scheduledDate;
}
static Future showWeeklyScheduledNotification({
int id = 8,
String? title,
String? body,
String? payload,
required DateTime scheduledDate,
}) async =>
_notification.zonedSchedule(
id,
title,
body,
_scheduleWeekly(const Time(17), days: [
DateTime.tuesday,
DateTime.friday,
DateTime.saturday,
DateTime.sunday,
]),
// tz.TZDateTime.from(scheduledDate, tz.local),
await _notificationDetails(),
payload: payload,
androidAllowWhileIdle: true,
uiLocalNotificationDateInterpretation:
UILocalNotificationDateInterpretation.absoluteTime,
matchDateTimeComponents: DateTimeComponents.dayOfWeekAndTime,
);
static void cancelAll() => _notification.cancelAll();
}
On the main function, init the NotificationApi as follows:
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
//__________________________________Notification and Time Zone
tz.initializeTimeZones();
await NotificationApi.init();
await NotificationApi.init(initScheduled: true);
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
#override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
// This widget is the root of your application.
///_____________________Init state initialising notifications
#override
void initState() {
loadAllNotifications;
super.initState();
}
loadAllNotifications() {
NotificationApi.showWeeklyScheduledNotification(
title: '🏆 New Deals Available 🏆',
body: '✨ Don\'t miss your opportunity to win BIG 💰💰',
scheduledDate: DateTime.now().add(const Duration(seconds: 12)));
NotificationApi.init(initScheduled: true);
listenNotifications();
}
//___________________________Listen to Notifications
void listenNotifications() =>
NotificationApi.onNotifications.stream.listen(onClickedNotification);
//__________________________On Notification Clicked
void onClickedNotification(String? payload) => Navigator.of(context).push(
MaterialPageRoute(builder: (context) => AppWrapper(updates: updates)));
//________________________________________Widget Build
#override
Widget build(BuildContext context) => MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Alpha Deals',
home: MyHomePage()
);
}

Flutter: Local Notification Scheduling

I am trying to set a scheduled alarm notification from the user selected date and time which i used showDatePicker for code below
DateTime _selectedDateAndTime;
Future _selectDayAndTimeL(BuildContext context) async {
DateTime _selectedDay = await showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(2021),
lastDate: DateTime(2030),
builder: (BuildContext context, Widget child) => child);
TimeOfDay _selectedTime = await showTimePicker(
context: context,
initialTime: TimeOfDay.now(),
);
if (_selectedDay != null && _selectedTime != null) {
//a little check
}
setState(() {
_selectedDateAndTime = DateTime(
_selectedDay.year,
_selectedDay.month,
_selectedDay.day,
_selectedTime.hour,
_selectedTime.minute,
);
// _selectedDate = _selectedDay;
});
// print('...');
}
which after the date and time has been selected the value is formatted like in the picture bellow
Now i want to be able to set the Scheduled Notification using the value from the selection but not sure how to do it... i have installed Flutter_Local_Notification and have imported it to my main.dart, have set the permission in the manifest file and have also tried to initial the plugin like down bellow
FlutterLocalNotificationsPlugin fltrNotification;
String _selectedParam;
int val;
#override
void initState() {
super.initState();
var androidInitilize = new AndroidInitializationSettings('app_icon');
var iOSinitilize = new IOSInitializationSettings();
var initilizationsSettings =
new InitializationSettings(androidInitilize, iOSinitilize);
fltrNotification = new FlutterLocalNotificationsPlugin();
fltrNotification.initialize(initilizationsSettings,
onSelectNotification: notificationSelected);
}
and i have also added the app_icon.png to my drawable folder
i have tried to follow some tutorial on how to do it but most of them only show how to set the netification using seconds but for my own project i want to set the schedule for a particular day, hour and minute
please how can i achive that?
You can use this my helper class
class NotificationPlugin {
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin;
var initializationSettings;
NotificationPlugin._() {
init();
}
init() async {
flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
if (Platform.isIOS) {
_requestIOSPermission();
}
initializePlatformSpecifics();
}
initializePlatformSpecifics() {
var initializationSettingsAndroid = AndroidInitializationSettings(
'mipmap/ic_launcher'); // <- default icon name is #mipmap/ic_launcher
var initializationSettingsIOS =
IOSInitializationSettings(onDidReceiveLocalNotification: (int a, String b, String c, d) {});
var initializationSettings =
InitializationSettings(initializationSettingsAndroid, initializationSettingsIOS);
flutterLocalNotificationsPlugin.initialize(initializationSettings,
onSelectNotification: (String s) {});
initializationSettings =
InitializationSettings(initializationSettingsAndroid, initializationSettingsIOS);
}
_requestIOSPermission() {
flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<IOSFlutterLocalNotificationsPlugin>()
.requestPermissions(alert: false, badge: true, sound: true);
}
setOnNotificationClick(Function onNotificationClick) async {
await flutterLocalNotificationsPlugin.initialize(
initializationSettings,
onSelectNotification: (payload) async {
onNotificationClick(payload);
},
);
}
Future<void> showNotification(
{#required int id, #required String title, #required String body}) async {
var androidChannelSpecifics = AndroidNotificationDetails(
'CHANNEL_ID',
'CHANNEL_NAME',
'CHANNEL_DESCRIPTION',
importance: Importance.High,
priority: Priority.High,
);
var iosChannelSpecifics = IOSNotificationDetails();
var platformChannelSpecifics = NotificationDetails(
androidChannelSpecifics,
iosChannelSpecifics,
);
await flutterLocalNotificationsPlugin.show(id, title, body, platformChannelSpecifics,
payload: id.toString());
}
Future<void> showScheduledNotification(
{#required int id,
#required String title,
#required String body,
#required String date}) async {
var scheduledNotificationDateTime = DateTime.parse(date);
var androidPlatformChannelSpecifics = AndroidNotificationDetails(
'your other channel id', 'your other channel name', 'your other channel description');
var iOSPlatformChannelSpecifics = IOSNotificationDetails();
NotificationDetails platformChannelSpecifics =
NotificationDetails(androidPlatformChannelSpecifics, iOSPlatformChannelSpecifics);
await flutterLocalNotificationsPlugin.schedule(
id, '$title', ' $body', scheduledNotificationDateTime, platformChannelSpecifics,
androidAllowWhileIdle: true);
}
Future<void> removeNotifications() async {
await flutterLocalNotificationsPlugin.cancelAll();
}
}
NotificationPlugin notificationPlugin = NotificationPlugin._();
and then you can call
await notificationPlugin.showScheduledNotification(
id: 123,
title:"fancy title",
body: "data",
date: yourDate,
);
/////////////////////////////////
if you will not use the helper class
this is simply what you need
var scheduledNotificationDateTime = DateTime.parse(date); // replace whith your date
var androidPlatformChannelSpecifics = AndroidNotificationDetails(
'your other channel id', 'your other channel name', 'your other channel description');
var iOSPlatformChannelSpecifics = IOSNotificationDetails();
NotificationDetails platformChannelSpecifics =
NotificationDetails(androidPlatformChannelSpecifics, iOSPlatformChannelSpecifics);
await flutterLocalNotificationsPlugin.schedule(
id, '$title', ' $body', scheduledNotificationDateTime, platformChannelSpecifics,
androidAllowWhileIdle: true);