Flutter开发之flutter_local_notifications

flutter_local_notifications 消息通知

flutter_local_notifications地址

dart 复制代码
flutter_local_notifications: ^18.0.1
dart 复制代码
class NotificationHelper {
  //工厂模式调用该类时,默认调用此方法,将实例对象返回出去
  static NotificationHelper? _instance = null;

  static NotificationHelper getInstance() {
    _instance ??= NotificationHelper._initial();
    return _instance!;
  }

  factory NotificationHelper() => _instance ??= NotificationHelper._initial();

  //创建命名构造函数
  NotificationHelper._initial() {
    initialize();
  }


  // FlutterLocalNotificationsPlugin实例
  final FlutterLocalNotificationsPlugin _notificationsPlugin =
  FlutterLocalNotificationsPlugin();

  // 常量定义
  static const String _channelId = 'your.channel.id';
  static const String _channelName = 'your channel name';
  static const String _channelDescription = 'your channel description';
  static const String _ticker = 'ticker';
  static const String _darwinNotificationCategoryPlain = 'plainCategory';

  // 初始化通知插件
  Future<void> initialize() async {
    try {
      final AndroidInitializationSettings initializationSettingsAndroid =
      AndroidInitializationSettings('@mipmap/ic_launcher');
      final DarwinInitializationSettings initializationSettingsIOS =
      DarwinInitializationSettings();
      final InitializationSettings initializationSettings =
      InitializationSettings(
          android: initializationSettingsAndroid,
          iOS: initializationSettingsIOS);
      await _notificationsPlugin.initialize(initializationSettings);
    } catch (e) {
      print('初始化通知插件失败: $e');
    }
  }

  Future<void> requestNotificationPermissions() async {
    if (await Permission.notification.isDenied) {
      final status = await Permission.notification.request();
      final status1 = await Permission.scheduleExactAlarm.request();
      LogUtils.d("requestNotificationPermissions :通知权限status1 $status1");
      if (status.isGranted) {
        LogUtils.d("requestNotificationPermissions :通知权限已授予");
        print('通知权限已授予');
      } else {
        LogUtils.d("requestNotificationPermissions :通知权限被拒绝");
        print('通知权限被拒绝');
      }
    } else {
      LogUtils.d("requestNotificationPermissions :通知权限已授予");
      print('通知权限已授予');
    }
  }

  // 显示通知
  Future<void> showNotification(
      {required String title, required String body}) async {
    try {
      final AndroidNotificationDetails androidNotificationDetails =
      AndroidNotificationDetails(
          _channelId, _channelName,
          channelDescription: _channelDescription,
          importance: Importance.max,
          priority: Priority.high,
          ticker: _ticker);

      final DarwinNotificationDetails iosNotificationDetails =
      DarwinNotificationDetails(
          categoryIdentifier: _darwinNotificationCategoryPlain);

      final NotificationDetails platformChannelSpecifics =
      NotificationDetails(
          android: androidNotificationDetails, iOS: iosNotificationDetails);

      await _notificationsPlugin.show(
        1,
        title,
        body,
        platformChannelSpecifics,
      );
    } catch (e) {
      print('显示通知失败: $e');
    }
  }

  // 周期性通知
  Future<void> scheduleNotification({
    required int id,
    required String title,
    required String body,
  }) async {
    const AndroidNotificationDetails androidNotificationDetails =
    AndroidNotificationDetails('your.channel.id', 'your channel name',
        channelDescription: 'your channel description',
        importance: Importance.max,
        priority: Priority.high,
        ticker: 'ticker');

    // ios的通知
    const String darwinNotificationCategoryPlain = 'plainCategory';
    const DarwinNotificationDetails iosNotificationDetails =
    DarwinNotificationDetails(
      categoryIdentifier: darwinNotificationCategoryPlain, // 通知分类
    );
    // 创建跨平台通知
    const NotificationDetails platformChannelSpecifics = NotificationDetails(
        android: androidNotificationDetails, iOS: iosNotificationDetails);
// 发起通知
    await _notificationsPlugin.periodicallyShow(
        id, title, body, RepeatInterval.everyMinute, platformChannelSpecifics);
  }


// 定时通知
  Future<void> zonedScheduleNotification({required int id,
    required String title,
    required String body,
    required DateTime scheduledDateTime}) async {
    const AndroidNotificationDetails androidNotificationDetails =
    AndroidNotificationDetails('10001', '唤醒',
        channelDescription: 'your channel description',
        importance: Importance.max,
        priority: Priority.high,
        ticker: 'ticker');

    // ios的通知
    const String darwinNotificationCategoryPlain = 'plainCategory';
    const DarwinNotificationDetails iosNotificationDetails =
    DarwinNotificationDetails(
      categoryIdentifier: darwinNotificationCategoryPlain, // 通知分类
    );
    // 创建跨平台通知
    const NotificationDetails platformChannelSpecifics = NotificationDetails(
        android: androidNotificationDetails, iOS: iosNotificationDetails);

    // 获取本地时区
    final location = tz.getLocation(tz.local.name);
    // 发起通知
     _notificationsPlugin.zonedSchedule(
      id, title, body,
      TZDateTime.from(scheduledDateTime, location), // 使用本地时区的时间
      platformChannelSpecifics,
      uiLocalNotificationDateInterpretation:
      UILocalNotificationDateInterpretation.wallClockTime, // 设置通知的触发时间是觉得时间
    );
  }


  /// 取消全部通知
  cancelAll(){
    _notificationsPlugin.cancelAll();
  }

  /// 取消对应ID的通知
  cancelId(int id){
    _notificationsPlugin.cancel(id);
  }
}

使用步骤:

0.请求通知权限

android

manifest.xml

dart 复制代码
<uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>
<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />

ios

Info.plist

dart 复制代码
<key>NSUserNotificationAlertIdentifier</key>
<string>我们需要您的许可来发送通知</string>
<key>NSUserNotificationAlertTitle</key>
<string>请求通知权限</string>
<key>NSUserNotificationAlertBody</key>
<string>我们希望能够在您允许的情况下发送通知。</string>

使用之前一定要代码里边获取通知权限

dart 复制代码
NotificationHelper.getInstance().requestNotificationPermissions();

1.初始化

dart 复制代码
NotificationHelper.getInstance().initialize();

2.使用

dart 复制代码
NotificationHelper.getInstance().zonedScheduleNotification(id: 10001, title: "科学研究", body: "研究开始了", scheduledDateTime: DateUtilss.getNowDateMs15or25DateTime(15));
相关推荐
minos.cpp2 小时前
Mac上Stable Diffusion的环境搭建(还算比较简单)
macos·ai作画·stable diffusion·aigc
追光天使14 小时前
Mac/Linux 快速部署TiDB
linux·macos·tidb
wzkttt15 小时前
Mac gfortran编译fortran出错
macos·gfortran
刘小哈哈哈17 小时前
iOS 多个输入框弹出键盘处理
macos·ios·cocoa
sunly_18 小时前
Flutter:导航,tab切换,顶部固定,列表分页滚动
开发语言·javascript·flutter
敲代码的小强19 小时前
Flutter项目兼容鸿蒙Next系统
flutter·华为·harmonyos
草明21 小时前
macOS 显示或不显示隐藏文件
macos
刘贤松21 小时前
构建MacOS应用小白教程(打包 & 签名 & 公证 & 上架)
macos
power_to_go21 小时前
macOS 配置 vscode 命令行启动
ide·vscode·macos
南山十一少21 小时前
在 Mac M2 上安装 PyTorch 并启用 MPS 加速的详细教程与性能对比
macos