Reputation: 1
I want that after I put time on text edit field the it will send notification on particular time but normal notification for current time is coming but notification for later is not works
I am using local notification https://pub.dev/packages?q=flutter+local+notification[text] NotificationService
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:timezone/data/latest.dart' as tz;
import 'package:timezone/timezone.dart' as tz;
// Define the background notification response handler
void backgroundNotificationResponseHandler(NotificationResponse notification) async {
print('Received background notification response: $notification');
// Handle the background notification response here
}
class NotificationService {
final FlutterLocalNotificationsPlugin notificationPlugin = FlutterLocalNotificationsPlugin();
Future<void> initNotification() async {
// Initialize the timezone package
tz.initializeTimeZones();
const AndroidInitializationSettings initializationAndroidSettings = AndroidInitializationSettings('logo');
final DarwinInitializationSettings initializationSettingIOS = DarwinInitializationSettings(
requestAlertPermission: true,
defaultPresentSound: true,
defaultPresentAlert: true,
requestBadgePermission: true,
requestSoundPermission: true,
onDidReceiveLocalNotification: (id, title, body, payload) async {
print('Received local notification: $id, $title, $body, $payload');
},
);
final InitializationSettings initializationSettings = InitializationSettings(
android: initializationAndroidSettings,
iOS: initializationSettingIOS,
);
await notificationPlugin.initialize(
initializationSettings,
onDidReceiveBackgroundNotificationResponse: backgroundNotificationResponseHandler,
);
// Request exact alarm permission for Android 12+
await requestExactAlarmPermission();
}
Future<void> requestExactAlarmPermission() async {
if (await Permission.scheduleExactAlarm.isDenied) {
await Permission.scheduleExactAlarm.request();
}
}
Future<void> showNotification({
int id = 0,
String? title,
String? body,
String? payload,
}) async {
print('Showing notification: $id, $title, $body, $payload');
await notificationPlugin.show(
id,
title,
body,
await notificationDetails(),
payload: payload,
);
}
Future<NotificationDetails> notificationDetails() async {
return const NotificationDetails(
iOS: DarwinNotificationDetails(),
android: AndroidNotificationDetails(
'channelId',
'channelName',
importance: Importance.max,
priority: Priority.high,
),
);
}
Future<void> scheduleNotification({
int id = 0,
String? title,
String? body,
String? payload,
required DateTime scheduledDate,
}) async
{
// Specify the Indian timezone
final location = tz.getLocation('Asia/Kolkata');
// Create a TZDateTime object in the Indian timezone
if (scheduledDate.isBefore(DateTime.now())){
final tz.TZDateTime scheduledTZDate = tz.TZDateTime.from(scheduledDate, location);
await notificationPlugin.zonedSchedule(
id,
title,
body,
scheduledTZDate,
await notificationDetails(),
payload: payload,
uiLocalNotificationDateInterpretation: UILocalNotificationDateInterpretation.absoluteTime,
androidAllowWhileIdle: true,
);
}
}
Future<void> cancelNotification(int id) async {
await notificationPlugin.cancel(id);
}
}
and TimeView.dart
import 'package:basics/model/TimeModel.dart';
import 'package:basics/services/notification_service.dart';
import 'package:basics/widget_helper/textbutton.dart';
import 'package:basics/widget_helper/widget_helper.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
class Timeview extends StatefulWidget {
const Timeview({super.key});
@override
State<Timeview> createState() => _TimeviewState();
}
class _TimeviewState extends State<Timeview> {
List<TimeModel> timerList = [];
final NotificationService _notificationService = NotificationService();
@override
Widget build(BuildContext context) {
return Scaffold(
body: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(height: 60,),
Text("Reminder"),
for (int i = 0; i < timerList.length; i++)
getTimerList(timerList[i], i, () {
setState(() {
});
}),
TextButton(
onPressed: () {
timerList.add(TimeModel());
setState(() {
});
},
child: getTxtColor(
msg: "+ Add More Time",
txtColor: Colors.black,
fontWeight: FontWeight.w500,
fontSize: 15)),
],
),
),
);
}
Widget getTimerList(TimeModel item, int index, Function onTap) {
TextEditingController medicineTimeCont = TextEditingController();
TextEditingController periodCont = TextEditingController();
if (item.time?.isEmpty == false && item.time != "null") {
medicineTimeCont.text = "${item.time}";
periodCont.text = "${item.timeFormat}";
}
return Padding(
padding: const EdgeInsets.all(4.0),
child: SizedBox(
height: 40,
width: double.infinity,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Flexible(
flex: 3,
child: edtRectField(
hint: "Select Time",
control: medicineTimeCont,
isReadOnly: true,
onTap: () {
displayTimePicker(
(String time, String format,
DateTime selectedDateTime){
timerList[index] = TimeModel(time: time,timeFormat: format);
onTap();
_scheduleNotification(selectedDateTime, index);
_testNotification();
}
);
})),
const SizedBox(width: 6),
Flexible(
flex: 2,
child: edtRectField(
control: periodCont,
hint: "Time",
isReadOnly: true,
onTap: () {
displayTimePicker(
(String time, String format,
DateTime selectedDateTime){
timerList[index] = TimeModel(time: time,timeFormat: format);
onTap();
_scheduleNotification(selectedDateTime, index);
}
);
})),
Flexible(
flex: 1,
child: IconButton(
onPressed: () {
timerList.removeAt(index);
onTap();
_cancelNotification(index);
},
icon: const Icon(Icons.clear)))
])),
);
}
Future displayTimePicker(
Function(String time, String formate, DateTime selectedDateTime)
selectedTimeClick) async {
TimeOfDay now = TimeOfDay.now();
TimeOfDay adjustedTime = TimeOfDay(hour: now.hour,minute: now.minute);
await showTimePicker(context: context, initialTime:adjustedTime)
.then((selectedTime) {
if (selectedTime != null) {
DateTime now = DateTime.now();
DateTime selectedDateTime = DateTime(now.year, now.month, now.day,
selectedTime.hour, selectedTime.minute);
String formattedTime = DateFormat('hh:mm').format(selectedDateTime);
final period = selectedTime.period == DayPeriod.am ? 'AM' : 'PM';
selectedTimeClick(formattedTime, period, selectedDateTime);
}
});
}
void _scheduleNotification(DateTime dateTime, int index) {
_notificationService.scheduleNotification(
id: index,
body: "Reminder",
payload: "now",
title: "New Notification",
scheduledDate: dateTime,
);
}
void _cancelNotification(int id) {
_notificationService.cancelNotification(id);
}
void _testNotification() async {
await _notificationService.showNotification(
id: 0,
title:timerList[0].time.toString(),
body: 'This is a test notification',
);
}
}
like + Add More Time I will select time for reminder and it will for only one day like I set a alarm and I am working json no shared preference , no db
Upvotes: 0
Views: 21