Reputation: 1
SO i was trying to send notification to the user, and wrote this code, basically its more like a reminder app, user will create a reminder and my app will give them a notification on exact time. every function works just fine but notification is not showing on real devices, on emulator it shows notification btw.
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:awesome_notifications/awesome_notifications.dart';
import 'dart:convert';
import 'package:table_calendar/table_calendar.dart';
import 'dart:io'; // Import for platform checking
class GcalcScreen extends StatefulWidget {
@override
_GcalcScreenState createState() => _GcalcScreenState();
}
class _GcalcScreenState extends State<GcalcScreen> {
bool isDarkMode = false;
List<Map<String, dynamic>> reminders = [];
int nextReminderId = 1; // Increment for each reminder
DateTime selectedDate = DateTime.now();
TimeOfDay selectedTime = TimeOfDay.now();
@override
void initState() {
super.initState();
_loadThemePreference();
_loadReminders();
_initializeNotifications();
_requestNotificationPermissions(); // Request notification permissions
}
// Load the theme preference from SharedPreferences
void _loadThemePreference() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
isDarkMode = prefs.getBool('isDarkMode') ?? false;
});
}
// Initialize Awesome Notifications
void _initializeNotifications() {
AwesomeNotifications().initialize(
'resource://drawable/res_app_icon',
[
NotificationChannel(
channelKey: 'gcalc_channel',
channelName: 'Graphics Calculator Notifications',
channelDescription: 'Notification channel for graphics calculator',
defaultColor: Color(0xFF9D50DD),
ledColor: Colors.white,
importance: NotificationImportance.High,
),
],
);
}
// Request notification permissions
void _requestNotificationPermissions() async {
if (Platform.isAndroid) {
final status = await AwesomeNotifications().isNotificationAllowed();
if (!status) {
AwesomeNotifications().requestPermissionToSendNotifications();
}
}
}
// Load reminders from SharedPreferences
void _loadReminders() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
String? remindersString = prefs.getString('reminders');
if (remindersString != null) {
List<dynamic> jsonList = json.decode(remindersString);
reminders = jsonList.map((item) => Map<String, dynamic>.from(item)).toList();
nextReminderId = reminders.isNotEmpty ? reminders.last['id'] + 1 : 1; // Update next reminder ID
}
setState(() {});
}
// Save reminders to SharedPreferences
void _saveReminders() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString('reminders', json.encode(reminders));
}
// Method to send a reminder notification
void _sendReminder(String message, DateTime dateTime, bool isActive, int id) {
if (isActive) {
AwesomeNotifications().createNotification(
content: NotificationContent(
channelKey: 'gcalc_channel',
id: id,
title: 'Reminder!',
body: message,
),
schedule: NotificationCalendar(
year: dateTime.year,
month: dateTime.month,
day: dateTime.day,
hour: dateTime.hour,
minute: dateTime.minute,
second: 0,
millisecond: 0,
preciseAlarm: true,
),
);
}
}
// Show dialog for setting a reminder
void _setReminder() {
String reminderMessage = '';
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text("Set Reminder"),
content: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Card(
child: Padding(
padding: const EdgeInsets.all(10.0),
child: TextField(
onChanged: (value) {
reminderMessage = value;
},
decoration: InputDecoration(
hintText: "Enter reminder message",
border: OutlineInputBorder(),
),
),
),
),
SizedBox(height: 10),
Text("Select Time:"),
ElevatedButton(
onPressed: () async {
TimeOfDay? pickedTime = await showTimePicker(
context: context,
initialTime: selectedTime,
);
if (pickedTime != null) {
selectedTime = pickedTime;
}
},
child: Text("Pick Time"),
),
],
),
),
actions: [
TextButton(
onPressed: () {
if (reminderMessage.isNotEmpty) {
DateTime reminderDateTime = DateTime(
selectedDate.year,
selectedDate.month,
selectedDate.day,
selectedTime.hour,
selectedTime.minute,
);
_sendReminder(reminderMessage, reminderDateTime, true, nextReminderId);
reminders.add({
'id': nextReminderId,
'message': reminderMessage,
'dateTime': reminderDateTime.toIso8601String(),
'isActive': true,
});
nextReminderId++;
_saveReminders();
// Call setState to refresh the UI
setState(() {});
Navigator.of(context).pop();
}
},
child: Text("Set"),
),
TextButton(
onPressed: () {
Navigator.of(context).pop();
},
child: Text("Cancel"),
),
],
);
},
);
}
// Method to cancel a reminder
void _cancelReminder(int id) {
AwesomeNotifications().cancel(id);
reminders.removeWhere((reminder) => reminder['id'] == id);
_saveReminders();
setState(() {});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Reminders"),
backgroundColor: Colors.transparent,
),
body: Container(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage(
isDarkMode
? 'Asset/images/bg_dark.png' // Dark mode background
: 'Asset/images/bg_light.png', // Light mode background
),
fit: BoxFit.cover,
),
),
child: Column(
children: [
// Calendar Widget
TableCalendar(
focusedDay: selectedDate,
firstDay: DateTime.utc(2020, 1, 1),
lastDay: DateTime.utc(2030, 12, 31),
selectedDayPredicate: (day) => isSameDay(selectedDate, day),
onDaySelected: (selectedDay, focusedDay) {
setState(() {
selectedDate = selectedDay;
});
},
),
SizedBox(height: 10),
// Reminders Card
Expanded(
child: Card(
elevation: 8, // Increased elevation for the card
child: reminders.isNotEmpty
? ListView.separated(
itemCount: reminders.length,
separatorBuilder: (context, index) => Divider(),
itemBuilder: (context, index) {
final reminder = reminders[index];
DateTime reminderDateTime = DateTime.parse(reminder['dateTime']);
String formattedTime = "Time: ${reminderDateTime.hour}:${reminderDateTime.minute.toString().padLeft(2, '0')}";
String formattedDate = "Date: ${reminderDateTime.day}/${reminderDateTime.month}/${reminderDateTime.year}";
return Dismissible(
key: Key(reminder['id'].toString()),
background: Container(
color: Colors.red,
alignment: Alignment.centerLeft,
padding: EdgeInsets.symmetric(horizontal: 20),
child: Icon(
Icons.delete,
color: Colors.white,
size: 30,
),
),
onDismissed: (direction) {
_cancelReminder(reminder['id']);
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text("Reminder deleted")),
);
},
child: ListTile(
title: Text(reminder['message']),
subtitle: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(formattedTime),
Text(formattedDate),
],
),
trailing: Switch(
value: reminder['isActive'],
onChanged: (value) {
setState(() {
reminder['isActive'] = value;
if (value) {
_sendReminder(
reminder['message'],
reminderDateTime,
true,
reminder['id'],
);
} else {
AwesomeNotifications().cancel(reminder['id']);
}
_saveReminders();
});
},
),
),
);
},
)
: Center(
child: Text(
"No reminders set.",
style: TextStyle(
color: isDarkMode ? Colors.white : Colors.black,
fontSize: 24,
),
),
),
),
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _setReminder, // Show dialog to set reminder
child: Icon(Icons.add),
),
);
}
}
So, i thought it was a problem in my code, so i tried out example code of awesome notification package and got the same result, notifications are showing on emulator but nothing is coming up on real devices
Upvotes: 0
Views: 108
Reputation: 134
Connect the device to your system and log it to see what it logs
flutter logs
In Android 13, which is API 33 and later, have you given permission separately in AndroidManifest.xml?
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
Upvotes: 0