Im trying to schedule a local notification in my flutter app but it doesnt show, it doesnt trigger any error or exception, just doesnt appear in my screen
I have tried to debbug the app but it didnt help with anything, chatGPT4 didnt help me either.
NotificationService:
import 'dart:convert';
import 'package:flutter/widgets.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:prj_unyclub/constants/appRoutes.dart';
import 'package:prj_unyclub/main.dart';
import 'package:timezone/timezone.dart' as tz;
class CustomNotification {
final int id;
final String? title;
final String? body;
final String? payload;
CustomNotification({
required this.id,
required this.title,
required this.body,
required this.payload,
});
}
class NotificationService {
NotificationService();
final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
Future<void> init() async {
const AndroidInitializationSettings initializationSettingsAndroid =
AndroidInitializationSettings("@mipmap/ic_launcher");
const InitializationSettings initializationSettings =
InitializationSettings(android: initializationSettingsAndroid);
await flutterLocalNotificationsPlugin.initialize(
initializationSettings,
onDidReceiveNotificationResponse: (NotificationResponse response) {
if (response.payload != null) {
selectNotificationStream.add(response.payload);
}
},
onDidReceiveBackgroundNotificationResponse: _onSelectedNotification,
);
selectNotificationStream.stream.listen((String? payload) {
if (payload != null && payload.isNotEmpty) {
AppRoutes.navigatorKey!.currentState!.pushNamed(payload);
}
});
}
static _onSelectedNotification(NotificationResponse? response) async {
if (response?.payload != null) {
String payloadCoded = response!.payload!;
var payload = jsonDecode(payloadCoded);
print('payload: ${payload['route']}');
selectNotificationStream.add(payload['route']);
}
}
Future<void> showNotification(CustomNotification notification) async {
// Verifica se payload é nulo antes de prosseguir
if (notification.payload == null) return;
const AndroidNotificationDetails androidDetails =
AndroidNotificationDetails(
'unyclubNotification',
'Unyclub',
channelDescription: "Este canal é para todas as notificaçõs do unyclub",
importance: Importance.high,
priority: Priority.max,
);
const DarwinNotificationDetails iOSDetails = DarwinNotificationDetails(
presentBadge: true,
presentAlert: true,
presentBanner: true,
);
await flutterLocalNotificationsPlugin.show(
notification.id,
notification.title,
notification.body,
const NotificationDetails(android: androidDetails, iOS: iOSDetails),
payload: notification.payload,
);
}
Future<void> scheduleNotification(
CustomNotification notification,
DateTime scheduledDate,
) async {
// Verifica se payload é nulo antes de prosseguir
if (notification.payload == null) return;
// Detalhes da notificação para Android
const AndroidNotificationDetails androidDetails =
AndroidNotificationDetails(
'unyclubNotification',
'Unyclub',
channelDescription: "Este canal é para todas as notificações do unyclub",
importance: Importance.high,
priority: Priority.max,
);
// Detalhes da notificação para iOS
const DarwinNotificationDetails iOSDetails = DarwinNotificationDetails(
presentBadge: true,
presentAlert: true,
presentSound: true,
);
// Configuração de detalhes de notificação para ambas as plataformas
NotificationDetails platformDetails =
const NotificationDetails(android: androidDetails, iOS: iOSDetails);
// Agendando a notificação
await flutterLocalNotificationsPlugin.zonedSchedule(
notification.id,
notification.title,
notification.body,
tz.TZDateTime.from(
scheduledDate,
tz.local,
), // Assegura-se de que a data agendada está no fuso horário local
platformDetails,
androidScheduleMode: AndroidScheduleMode.exactAllowWhileIdle,
payload: notification.payload,
uiLocalNotificationDateInterpretation:
UILocalNotificationDateInterpretation.absoluteTime,
);
}
checkForNotifications() async {
final details =
await flutterLocalNotificationsPlugin.getNotificationAppLaunchDetails();
if (details != null && details.didNotificationLaunchApp) {
_onSelectedNotification(details.notificationResponse);
}
}
}
Main:
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Permission.notification.isDenied.then((value) {
if (value) {
Permission.notification.request();
}
});
await Permission.scheduleExactAlarm.isDenied.then((value) {
if (value) {
Permission.scheduleExactAlarm.request();
}
});
await Firebase.initializeApp();
NotificationService notificationService = NotificationService();
await notificationService.init();
FirebaseMessagingService firebaseMessagingService =
FirebaseMessagingService();
firebaseMessagingService.initialize();
tz.initializeTimeZones();
final String timeZoneName = await FlutterNativeTimezone.getLocalTimezone();
tz.setLocalLocation(tz.getLocation(timeZoneName));
runApp(const MyApp());
}
ScheduleMethod
Future<void> scheduleMeetingsNotifications() async {
//? Carregando as reuniões
MeetingsController controller = MeetingsController(context: context);
List<Meetings> meetingsList = [];
await controller.loadMeetings("1").then((value) {
setState(() {
meetingsList = controller.getMeetingsList;
});
});
//? Pegando a data da ultima reunião
Meetings meeting = meetingsList[0];
DateTime notificationDate = DateFormat("dd/MM/yyyy")
.parse(meeting.dtMeeting!)
.subtract(const Duration(hours: 12));
//? Agendando a Notificação
NotificationService notificationService = NotificationService();
DateTime time = DateTime.now().add(const Duration(seconds: 10));
print("@@@@@@@@@@@@@@@@ $time @@@@@@@@@@@@@@@@@@@");
notificationService.scheduleNotification(
CustomNotification(
id: int.parse(meeting.id!),
title: meeting.topic!,
body: "A reunião começa",
payload: jsonEncode({"route": AppRoutes.meetingsScreen}),
),
time,
);
}
Im trying to send the notification 10 seconds after the method just for testing porpouses, also tried to send the notification 30 seconds and 1 minute after.
I have asked for the notifications permission in the main method but also put it in my android manifest since im testing in a android emulator