Flutter:预定的通知日期时间

Posted

技术标签:

【中文标题】Flutter:预定的通知日期时间【英文标题】:Flutter: Scheduled notification datetime 【发布时间】:2020-10-18 16:21:13 【问题描述】:

我希望将 Flutter 的插件 date_time_picker 与本地通知集成。

因此,当我选择日期和时间时,我也会安排通知。

这是我的代码..你能帮帮我吗?现在我没有任何错误,但代码不起作用。

 class test1 extends StatefulWidget 
  @override
  _test1State createState() => _test1State();


class _test1State extends State 
  FlutterLocalNotificationsPlugin fltrNotification;
  String _selectedParam;
  String task;
  int val;

  @override
  void initState() 
    super.initState();
    var androidInitilize =
        new AndroidInitializationSettings('icon_notification');
    var iosinitilize = new IOSInitializationSettings();
    var initilizationsSettings = new InitializationSettings(
        android: androidInitilize, iOS: iOSinitilize);
    fltrNotification = new FlutterLocalNotificationsPlugin();
    fltrNotification.initialize(initilizationsSettings,
        onSelectNotification: notificationSelected);
  

  Future scheuleAtParticularTime(DateTime timee) async 
    // var time = DateTime(timee.day, timee.month, timee.year, timee.hour,
    //     timee.minute, timee.second);
    var time =
        DateTime(timee.year, timee.month, timee.day, timee.hour, timee.minute);

    var scheduledNotificationDateTime =
        new DateTime.now().add(new Duration(seconds: 5));
    var androidPlatformChannelSpecifics = new AndroidNotificationDetails(
        'your other channel id',
        'your other channel name',
        'your other channel description');
    var iOSPlatformChannelSpecifics = new IOSNotificationDetails();
    NotificationDetails platformChannelSpecifics = new NotificationDetails(
        android: androidPlatformChannelSpecifics,
        iOS: iOSPlatformChannelSpecifics);
    // tz.initializeTimeZones();
    // tz.setLocalLocation(tz.getLocation('Italy'));
    await fltrNotification.schedule(1, 'scheduled title', 'scheduled body',
        scheduledNotificationDateTime, platformChannelSpecifics);
  

  @override
  Widget build(BuildContext context) 
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            FlatButton(
              onPressed: () 
                DatePicker.showDateTimePicker(context, showTitleActions: true,
                    onChanged: (date) 
                  print('change $date');
                , onConfirm: (date) 
                  print('confirm $date');
                  scheuleAtParticularTime(DateTime.fromMillisecondsSinceEpoch(
                      date.millisecondsSinceEpoch));
                , currentTime: DateTime.now(), locale: LocaleType.it);
              ,
              child: Text(
                'Select time for notification arrival',
                style:
                    TextStyle(color: Colors.black, fontWeight: FontWeight.w900),
              ),
            ),
          ],
        ),
      ),
    );
  

  Future notificationSelected(String payload) async 
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        content: Text("Notification Clicked $payload"),
      ),
    );
  


谢谢!

ps.. 我已经插入了完整的代码,通知工作但在随机时间(从选择器设置后大约 5 秒)

【问题讨论】:

您是否在 AndroidManifest.xml 文件中添加了权限请求? 当然,所有权限 您似乎遇到了编码错误。如果您觉得这对未来的其他人没有帮助,请考虑删除该问题。否则,请考虑再次清楚简短地陈述问题来改进问题,以便其他人会发现它有用。 【参考方案1】:

假设您已经配置了 AndroidManifest.xml 文件,这是用于为 Android 设置插件(IOS 没有那么不同),请注意这是针对 flutter_local_notifications 的 3.0.0 版本(我检查时的最后一个版本)。

首先是助手类:

import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:timezone/timezone.dart' as tz;

class NotificationsHelper 

  static final _flutterLocalNotificationsPlugin =
      FlutterLocalNotificationsPlugin();

//needs an icon
  static final _initializationSettingsAndroid =
      AndroidInitializationSettings('app_icon');

  static final _initializationSettings =
      InitializationSettings(android: _initializationSettingsAndroid);

  static Future<void> init() async 
    await _flutterLocalNotificationsPlugin.initialize(_initializationSettings);
    tz.initializeDatabase([]);
  

  static final _androidNotificationDetails = AndroidNotificationDetails(
    'channel id',
    'channel name',
    'channel description',
    importance: Importance.max,
    priority: Priority.high,
  );

  static final _notificationDetails =
      NotificationDetails(android: _androidNotificationDetails);

// set Notification methoud
 static Future<void> setNotification(DateTime dateTime, int id) async 
    await _flutterLocalNotificationsPlugin.zonedSchedule(
      id,
      'scheduled title',
      'scheduled body',
      tz.TZDateTime(tz.local, dateTime.year, dateTime.month, dateTime.hour,
          dateTime.minute),
      _notificationDetails,
      androidAllowWhileIdle: true,
      uiLocalNotificationDateInterpretation:
          UILocalNotificationDateInterpretation.absoluteTime,
    );
  

// cancel Notification methoud
 static Future<void> cancelNotification(int id) async 
    await _flutterLocalNotificationsPlugin.cancel(id);
  

AndroidInitializationSettings 需要一个图标,它应该在android\app\src\main\res\drawable 文件夹中,如果图标名称是 app_icon.png。

主函数中的第二个:

void main() async 
  WidgetsFlutterBinding.ensureInitialized();
  await NotificationsHelper.init();
  runApp(MyApp());

这将初始化插件。

现在,您可以在应用中的任何位置拨打NotificationsHelper.setNotification() 设置通知或拨打NotificationsHelper.cancelNotification() 取消通知。

id 应该是唯一的,因为您不能有 2 个或多个具有相同 id 的计划通知,您添加的最后一个通知将替换旧的。

【讨论】:

第一篇文章中的完整代码编辑,我已经初始化了插件。通知有效,但到达随机时间(我选择时间后大约 5 秒) tz.local 始终返回“UTC”,但设备时区为“IST”。【参考方案2】:

好的,我找到了问题:

await fltrNotification.schedule(1, 'scheduled title', 'scheduled body', timee, platformChannelSpecifics);

而不是

await fltrNotification.schedule(1, 'scheduled title', 'scheduled body',
        scheduledNotificationDateTime, platformChannelSpecifics);

【讨论】:

【参考方案3】:

您可以使用内置类来安排带有日期和时间的通知。您可以查看以下代码以更好地理解。

Future<void> scheduleNotification() async 

    var scheduledNotificationDateTime =
    DateTime(2021,10,11,1,17,0); //Here you can set your custom Date&Time

    var androidPlatformChannelSpecifics = AndroidNotificationDetails(
      'channel id',
      'channel name',
      'channel description',
      icon: 'flutter_devs',
      largeIcon: DrawableResourceAndroidBitmap('flutter_devs'),
    );
    var iOSPlatformChannelSpecifics = IOSNotificationDetails();
    var platformChannelSpecifics = NotificationDetails(
        androidPlatformChannelSpecifics, iOSPlatformChannelSpecifics);
    await flutterLocalNotificationsPlugin.schedule(
        0,
        'scheduled title',
        'scheduled body',
        scheduledNotificationDateTime,
        platformChannelSpecifics);
  

【讨论】:

以上是关于Flutter:预定的通知日期时间的主要内容,如果未能解决你的问题,请参考以下文章

如何阻止计划的本地通知在特定日期后触发?

每天安排不同的通知 Flutter

Node.js - FCM 发送预定主题通知

使用 quickblox 和 IOS sdk 实现预定的推送通知

如何在python中找到当前日期和预定日期的时间差? [复制]

将预定的日期时间值插入 SQL 表