Я работаю над кодом, который будет проверять список элементов, загружаемых из файла JSON, управляемых с помощью управления состоянием Riverpod, и отправлять локальные уведомления. Я прочитал официальную документацию по плагину локальных уведомлений. Я хочу использовать уведомления, чтобы информировать о товарах, срок выполнения которых истекает через 3 дня. Приложение работает нормально, но есть функция уведомлений. Я понимаю, что мне нужно инициализировать main и использовать диспетчер работ для управления уведомлениями, пока приложение находится в глубоком сне/не работает, но с помощью приведенного ниже подхода я не совсем понимаю, как это будет работать, потому что список элементов не инициализируется с помощью Riverpod государственного управления пока нет, но не знаю, с чего к этому подойти. Помимо запуска приложения выдается следующая ошибка:
main.dart:
@pragma('vm:entry-point')
void callbackDispatcher() {
Workmanager().executeTask((task, inputData) async {
await NotificationService().checkDueDate();
return Future.value(true);
});
}
Future main() async {
WidgetsFlutterBinding.ensureInitialized();
NotificationService().initialize();
Workmanager().initialize(callbackDispatcher);
Workmanager().registerPeriodicTask(
"dueDateChecker",
"dueDateCheckerTask",
frequency: const Duration(days: 1),
);
storage = Storage();
runApp(ProviderScope(child: MyApp()));
}
NotificationService.dart:
class NotificationService {
static final NotificationService _instance = NotificationService._internal();
factory NotificationService() {
return _instance;
}
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
NotificationService._internal();
Future initialize() async {
const AndroidInitializationSettings initializationSettingsAndroid =
AndroidInitializationSettings('app_icon');
const InitializationSettings initializationSettings =
InitializationSettings(
android: initializationSettingsAndroid,
);
//iOS: initializationSettingsDarwin);
await flutterLocalNotificationsPlugin.initialize(
initializationSettings,
onDidReceiveNotificationResponse: notificationTapForeground,
onDidReceiveBackgroundNotificationResponse: notificationTapBackground,
);
flutterLocalNotificationsPlugin
.getNotificationAppLaunchDetails()
.then((NotificationAppLaunchDetails? details) {
if (details != null && details.didNotificationLaunchApp) {
print("tapped when app is not running");
navigatorKey.currentState?.context.push("/inventory");
// TODO: Handle notification that caused the app to launch
// You can access details.notificationResponse.payload here
}
});
}
Future _showNotification(List items) async {
const AndroidNotificationDetails androidNotificationDetails =
AndroidNotificationDetails('0', 'Impending Due Date',
channelDescription: 'Impending Due Date Notification',
actions: [
AndroidNotificationAction('0', 'Go to Inventory'),
AndroidNotificationAction('1', 'Close'),
],
importance: Importance.max,
priority: Priority.high,
ticker: 'ticker');
const NotificationDetails notificationDetails =
NotificationDetails(android: androidNotificationDetails);
String dueItems = items.map((item) => item.name).join(', ');
await flutterLocalNotificationsPlugin.show(
0, 'Impending Due Date', 'Your $dueItems is due soon!',
notificationDetails,
payload: 'item x');
}
Future notificationTapBackground(
NotificationResponse notificationResponse) async {
switch (notificationResponse.actionId) {
case '0':
navigatorKey.currentState?.context.push("/inventory");
print('Action 1 was pressed');
break;
case '1':
print('Action 2 was pressed');
break;
default:
// Handle the main notification tap (if the notification itself was tapped, not an action button)
//print('Notification tapped, payload: ${notificationResponse.payload}');
}
}
Future notificationTapForeground(
NotificationResponse notificationResponse) async {
switch (notificationResponse.actionId) {
case '0':
navigatorKey.currentState?.context.push("/inventory");
print('Action 1 was pressed');
break;
case '1':
print('Action 2 was pressed');
break;
default:
// Handle the main notification tap (if the notification itself was tapped, not an action button)
//print('Notification tapped, payload: ${notificationResponse.payload}');
}
}
Future checkDueDate() async {
final currentItemList = ProviderContainer().read(jsonInventoryServiceNotifierProvider);
late var dueDateList;
currentItemList.when(
data: (item) {
dueDateList = item
.where((element) =>
element.dueDate != null &&
element.calculateDueDate() print("loading.."),
error: (e, st) => print("error.."),
);
_showNotification(dueDateList);
}
}
Ошибка при запуске приложения:
The backgroundHandler needs to be either a static function or a top level function to be accessible as a Flutter entry point.
Подробнее здесь: https://stackoverflow.com/questions/790 ... r-question
Flutter: локальные уведомления Android для запуска приложения с помощью диспетчера работ / Вопрос о правильном подходе ⇐ Android
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
Локальные уведомления, не поступающие в ios, реагируют на встроенные push-уведомления
Anonymous » » в форуме IOS - 0 Ответы
- 24 Просмотры
-
Последнее сообщение Anonymous
-