Flutter:flutter_local_notifications——消息推送的学习

前言

注: 刚开始学习,如果某些案例使用时遇到问题,可以自行百度、查看官方案例、官方github。

简介
Flutter Local Notifications是一个用于在Flutter应用程序中显示本地通知的插件。它提供了一个简单而强大的方法来在设备上发送通知,以便用户可以在应用程序处于后台或设备锁定状态下接收到它们。

使用Flutter Local Notifications插件,可以创建和安排各种类型的通知,包括:

  1. 即时通知:立即显示的通知,用于向用户传达重要消息或提醒。
  2. 周期性通知:可以按照指定的时间间隔重复显示的通知,例如每天或每周的提醒。
  3. 定时通知:在特定日期和时间触发的通知,用于安排未来事件或提醒。

通过使用Flutter Local Notifications,可以自定义通知的外观和行为,包括标题,内容,图标,声音,振动模式和点击操作。此外,还可以处理用户与通知的交互,例如当用户点击通知时执行特定的操作。

Flutter Local Notifications插件使用简单且易于集成到Flutter项目中。它提供了一组易于使用的API,可以轻松创建和管理通知。此外,它还兼容Android和iOS平台,并且可以在两个平台上以相同的代码库进行操作。

官方地址
https://pub-web.flutter-io.cn/packages/flutter_local_notifications

备注: 这里只学习关于安卓的基本使用

学习

准备

安装

flutter pub add flutter_local_notifications

即时通知

通知辅助类
NotificationHelper

// 导入包
import 'package:flutter_local_notifications/flutter_local_notifications.dart';

class NotificationHelper {
  // 使用单例模式进行初始化
  static final NotificationHelper _instance = NotificationHelper._internal();
  factory NotificationHelper() => _instance;
  NotificationHelper._internal();

  // FlutterLocalNotificationsPlugin是一个用于处理本地通知的插件,它提供了在Flutter应用程序中发送和接收本地通知的功能。
  final FlutterLocalNotificationsPlugin _notificationsPlugin =
      FlutterLocalNotificationsPlugin();

  // 初始化函数
  Future<void> initialize() async {
    // AndroidInitializationSettings是一个用于设置Android上的本地通知初始化的类
    // 使用了app_icon作为参数,这意味着在Android上,应用程序的图标将被用作本地通知的图标。
    const AndroidInitializationSettings initializationSettingsAndroid =
    AndroidInitializationSettings('@mipmap/ic_launcher');
    // 15.1是DarwinInitializationSettings,旧版本好像是IOSInitializationSettings(有些例子中就是这个)
    const DarwinInitializationSettings initializationSettingsIOS =
        DarwinInitializationSettings();
    // 初始化
    const InitializationSettings initializationSettings =
        InitializationSettings(
            android: initializationSettingsAndroid,
            iOS: initializationSettingsIOS);
    await _notificationsPlugin.initialize(initializationSettings);
  }

//  显示通知
  Future<void> showNotification(
      {required String title, required String body}) async {
    // 安卓的通知
    // 'your channel id':用于指定通知通道的ID。
    // 'your channel name':用于指定通知通道的名称。
    // 'your channel description':用于指定通知通道的描述。
    // Importance.max:用于指定通知的重要性,设置为最高级别。
    // Priority.high:用于指定通知的优先级,设置为高优先级。
    // 'ticker':用于指定通知的提示文本,即通知出现在通知中心的文本内容。
    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.show(
      1,
      title,
      body,
      platformChannelSpecifics,
    );
  }
}

使用

main() async {
  //用于确保Flutter的Widgets绑定已经初始化。
  WidgetsFlutterBinding.ensureInitialized();

  // 初始化通知帮助类
  NotificationHelper notificationHelper = NotificationHelper();
  await notificationHelper.initialize();
  runApp(const MyApp());
}
class SwitcherContainerState extends State<SwitcherContainer> {
  final NotificationHelper _notificationHelper = NotificationHelper();
  
  Widget build(BuildContext context) {
    return Center(
        child: ElevatedButton(
            onPressed: () {
              _notificationHelper.showNotification(
                title: 'Hello',
                body: 'This is a notification!',
              );
            },
            child: const Text("发起通知")));
  }
}

注意:

  • 一定要在main函数里进行初始化,不然会报下面这个错误(百度了半天,最后发现是自己忘记了初始化)
    在这里插入图片描述
  • 要开启应用的通知权限,不然可能无法通知

在这里插入图片描述

周期性通知

 // 周期性通知
  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);
  }
}

这里我设置的是每分钟通知一次,注意:假如你在10:01发起了通知,10:01不会有通知消息,而是从10:02开发每隔一分钟发起一次通知。

定时通知

// 定时通知
Future<void> zonedScheduleNotification(
    {required int id,
    required String title,
    required String body,
    required DateTime scheduledDateTime}) 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.zonedSchedule(
    id, title, body,
    tz.TZDateTime.from(scheduledDateTime, tz.local), // 使用本地时区的时间
    platformChannelSpecifics,
    uiLocalNotificationDateInterpretation:
        UILocalNotificationDateInterpretation.absoluteTime, // 设置通知的触发时间是觉得时间
  );
}

注意:如下图参数scheduledDateTZDateTime类型,看了一下官方示例,还需要下载timezone 库。
timezone 是一个用来处理时区信息的,可以使得在不同平台上创建和处理日期时间对象更加方便和准确。

官方地址
https://pub-web.flutter-io.cn/packages/timezone

安装

flutter pub add timezone

初始化
就在通知辅助类NotificationHelperinitialize函数里初始化一下就行

import 'package:timezone/timezone.dart' as tz;
import 'package:timezone/data/latest.dart' as tz;

//  初始化tz
tz.initializeTimeZones();

在这里插入图片描述
在这里插入图片描述

其他

除了上面三种外还有其他的通知形式,比如(以下内容没有测试)

长文本

final androidPlatformChannelSpecifics = AndroidNotificationDetails(
  'channel_id',
  'channel_name',
  'channel_description',
  styleInformation: BigTextStyleInformation('大文本内容'),
);

大图片

final androidPlatformChannelSpecifics = AndroidNotificationDetails(
  'channel_id',
  'channel_name',
  'channel_description',
  styleInformation: BigPictureStyleInformation(
    FilePathAndroidBitmap('图片路径'),
    largeIcon: FilePathAndroidBitmap('大图标路径'),
  ),
);

还有一些比如媒体样式、带进度条的等都可以在AndroidNotificationDetails找到相应的参数。
对于IOS来说,通知样式收到苹果的限制,可以通过DarwinNotificationDetailsattachments参数来实现一些简单操作。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/48738.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

PostgreSQL 查询json/jsonb是否存在某个片段

文章目录 前言实现实现思路坑1坑2坑3 恍然大悟 前言 在PostgreSQL中&#xff0c;jsonb有额外的操作符&#xff0c;如 >、<、?、?|、?& 可以用来查询是否包含路径/值&#xff0c;以及顶层键值是否存在。 详细文章&#xff1a;PostgreSQL 操作json/jsonb 那么&am…

青大数据结构【2021】

一、单选&#xff08;17&#xff01;&#xff09; 根据中序遍历得到降序序列可以知道&#xff0c;每个结点的左子树的结点的值比该结点的值小&#xff0c;因为没有重复的关键字&#xff0c;所以拥有最大值的结点没有左子树。 二、简答 三、分析计算 四、算法分析 3.迪杰斯特拉…

LLaMA2可商用|GPT-4变笨|【2023-0723】【第七期】

一、大咖观点&#xff1a; 傅盛&#xff1a;ChatGPT时代如何创业 - BOTAI - 博客园Google 已经被OpenAI 超越了吗&#xff1f;| AlphaGo 之父深度访谈《人民日报》&#xff1a;大模型的竞争&#xff0c;是国家科技战略的竞争WAIC 2023 | 张俊林&#xff1a;大语言模型带来的交…

贝塞尔曲线与B样条曲线

B-spline and Bezier Curve 介绍一下robotics运动规划方向的B样条曲线与贝塞尔曲线相关知识。 0728&#xff1a;TODO&#xff0c;节点向量如何得到&#xff1f; 贝塞尔曲线&#xff0c;B-样条&#xff0c;非均匀有理B样条梳理曲线篇: 贝塞尔曲线Animated Bzier CurvesBzier …

gin框架内容(三)--中间件

gin框架内容&#xff08;三&#xff09;--中间件 Gin框架允许开发者在处理请求的过程中&#xff0c;加入用户自己的函数。这个函数就叫中间件&#xff0c;中间件适合处理一些公共的业务逻辑&#xff0c;比如登录认证、权限校验、数据分页、记录日志、耗时统计等 即比如&#x…

【牛客面试必刷TOP101】Day1.反转链表和合并两个排序的链表

作者简介&#xff1a;大家好&#xff0c;我是未央&#xff1b; 博客首页&#xff1a;未央.303 系列专栏&#xff1a;牛客面试必刷TOP101 每日一句&#xff1a;人的一生&#xff0c;可以有所作为的时机只有一次&#xff0c;那就是现在&#xff01;&#xff01;&#xff01;&…

【Ansible】Ansible自动化运维工具的应用与常用命令

ansible自动化运维工具 一、ansible 的概述1. ansible 的概念2. ansible 的特性 二、ansible 的部署与命令1. ansible 的部署1.1 服务器ip地址设置1.2 ansible 服务器部署 2. ansible 命令行模块2.1 command 模块2.2 shell 模块2.3 cron 模块2.4 user 模块2.5 group 模块2.6 co…

财报解读:新鲜感褪去后,微软直面AI的骨感现实?

微软交出了一份远观尚可&#xff0c;但近看承压的“答卷”。 北京时间2023年7月26日&#xff0c;微软披露了2023财年第四财季及全年财报。受生产力和业务流程部门和智能云部门等业务带动&#xff0c;微软第四财季营收561.89亿美元&#xff0c;同比增长8%&#xff1b;净利润200…

【iOS】—— 持久化

文章目录 数据持久化的目的iOS中数据持久化方案数据持久化方式分类内存缓存磁盘缓存 沙盒机制获取应用程序的沙盒路径沙盒目录的获取方式 持久化数据存储方式XML属性列表Preferences偏好设置&#xff08;UserDefaults&#xff09;数据库存储什么是序列化和反序列化&#xff0c;…

TypeError: Failed to fetch dynamically imported module

浏览器报了如下错误&#xff1a; vue文件如下&#xff1a; 错误出现的原因是因为导入的是路径&#xff0c;vue会在该路径下的文件夹搜索所有文件&#xff0c;但是没有找到对应的组件&#xff0c;但是浏览器并不会直接禁止访问&#xff0c;而是在控制台报错&#xff0c;解决办法…

【雕爷学编程】Arduino动手做(174)---Sensor Shield V5.0传感器扩展板

37款传感器与执行器的提法&#xff0c;在网络上广泛流传&#xff0c;其实Arduino能够兼容的传感器模块肯定是不止这37种的。鉴于本人手头积累了一些传感器和执行器模块&#xff0c;依照实践出真知&#xff08;一定要动手做&#xff09;的理念&#xff0c;以学习和交流为目的&am…

k8s证书过期

k8s证书过期 [rootk8s-master102 ~]# kubectl get pod -A Unable to connect to the server: x509: certificate has expired or is not yet valid: current time 2023-07-25T15:14:0008:00 is after 2023-07-24T16:25:58Z解决方案 备份 kubernetes配置 cp -r /etc/kubernet…

【Python 实战】---- 批量识别图片中的文字,存入excel中【使用百度的通用文字识别】

分析 1. 获取信息图片示例 2. 运行实例 3. 运行结果 4. 各个文件的位置 实现 1. 需求分析 识别图片中的文字【采用百度的通用文字识别】;文字筛选,按照分类获取对应的文本;采用 openpyxl 实现将数据存入 excel 中。2. 获取 access_token 获取本地缓存的

谈谈你对Synchronized关键字的理解及使用

synchronized关键字最主要的三种使用方式的总结 修饰实例方法&#xff0c;作用于当前对象实例加锁&#xff0c;进入同步代码前要获得当前对象实例的锁修饰静态方法&#xff0c;作用于当前类对象加锁&#xff0c;进入同步代码前要获得当前类对象的锁 。也就是给当前类加锁&…

DFS之剪枝与优化--小猫爬山

思路&#xff1a;对小猫的数量和车箱数进行bfs&#xff0c;一旦小猫的数量达到n&#xff0c;就统计ans的数量&#xff0c;如果当前车的剩余重量无法再承受任意一个猫的重量&#xff0c;那么我们将车辆数1来保证小猫能够下山。 #include<bits/stdc.h> using namespace std…

芯片制造详解.净洁室的秘密.学习笔记(三)

这是芯片制造系列的第三期跟学up主三圈&#xff0c;这里对其视频内容做了一下整理和归纳&#xff0c;喜欢的可以看原视频。 芯片制造详解03&#xff1a; 洁净室的秘密&#xff5c;为何芯片厂缺人&#xff1f; 芯片制造详解.净洁室的秘密.学习笔记 三 简介一、干净的级别二、芯片…

Mybatis 新增/批量新增, 拿到返回的自增主键ID

单个新增 &#xff1a; /** * 插入菜单 * param menuInfo * return */ int insertMenuInfo(MenuInfo menuInfo); xml&#xff1a; <insert id"insertMenuInfo" parameterType"com.XXXX..MenuInfo" keyProperty"id&quo…

devops(后端)

1.前言 该devpos架构为gitlabjenkinsharbork8s&#xff0c;项目是java项目&#xff0c;流程为从gitlab拉取项目代码到jenkins&#xff0c;jenkins通过maven将项目代码打成jar包&#xff0c;通过dockerfile构建jdk环境的镜像并把jar包放到镜像中启动&#xff0c;构建好的镜像通…

系统集成项目管理工程师挣值分析笔记大全

系统集成项目管理工程师挣值分析笔记大全 挣值分析是一种项目管理技术&#xff0c;用于量化和监控项目绩效。它通过比较计划值&#xff08;PV&#xff09;、实际成本&#xff08;AC&#xff09;和挣值&#xff08;EV&#xff09;三个参数来评估项目的进展情况和成本绩效。 挣值…

flex布局进阶

推荐看一下阮一峰老师的flex布局博客【Flex 布局教程&#xff1a;语法篇】(https://www.ruanyifeng.com/blog/2015/07/flex-grammar.html#)&#xff0c;讲的非常清晰。 一、多行布局大小相同的子盒子技巧 使用弹性布局实现多行均匀布局时&#xff0c;如若子盒子数量不能被每行…