Я работаю над кодом, который будет проверять список элементов, загружаемых из файла 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
Форум для тех, кто программирует под Android
1728473984
Anonymous
Я работаю над кодом, который будет проверять список элементов, загружаемых из файла 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.
Подробнее здесь: [url]https://stackoverflow.com/questions/79070008/flutter-android-local-notifications-to-launch-app-using-work-manager-question[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия