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

news/2024/5/10 14:53:23

前言

注: 刚开始学习,如果某些案例使用时遇到问题,可以自行百度、查看官方案例、官方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.mrgr.cn/p/17473173

相关文章

flask 点赞系统

dianzan.html页面 <!DOCTYPE html> <html lang"en"> <head><meta charset"UTF-8"><title>点赞系统</title> </head> <body><h2>这是一个点赞系统</h2><table border"1"><…

数据分析-关于指标和指标体系

一、电商指标体系 二、指标体系的作用 三、统计学中基本的分析手段

Python+OpenCV实现自动扫雷,挑战扫雷世界记录!

目录 准备 - 扫雷软件 实现思路 - 01 窗体截取 - 02 雷块分割 - 03 雷块识别 - 04 扫雷算法实现 福利&#xff1a;文末有Python全套资料哦 我们一起来玩扫雷吧。用PythonOpenCV实现了自动扫雷&#xff0c;突破世界记录&#xff0c;我们先来看一下效果吧。 中级 - 0.74秒 …

HC32F448-小华MCU

由于要开发和学习使用低成本MCU&#xff0c;这里记录下小华半导体HC32F448的手册参数 芯片官网&#xff08;HC32F448MCTI-LQFP80&#xff09; 小华半导体有限公司 (xhsc.com.cn) HC32F448 系列MCU是32位的ARM Cortex-M4微控制器。最高工作频率 200MHz&#xff0c;最大 256KB 的…

css3的filter图片滤镜使用

业务介绍 默认&#xff1a;第一个图标为选中状态&#xff0c;其他三个图标事未选中状态 样式&#xff1a;选中状态是深蓝&#xff0c;未选中状体是浅蓝 交互&#xff1a;鼠标放上去选中&#xff0c;其他未选中&#xff0c;鼠标离开时候保持当前选中状态 实现&#xff1a;目前…

2023级学姐上岸浙江大学MBA的备考经验分享

在分享我的浙大MBA提面经验之前&#xff0c;先给大家炫一波前段时间刚收到的浙大录取通知书。还有一个月的时间我就要去梦想中的殿堂学习了&#xff0c;而针对今年报考浙大的考生来说&#xff0c;杭州这边还有最后两次可以参加提面的机会&#xff0c;我们去年这届共招收新生526…

kettle 学习笔记

kettle 学习笔记 个人理解下载 / 安装kettle及测试环境准备kattle下载安装JDK安装配置MySQL安装配置 使用练习创建数据库连接转换练习 个人理解 ETL工具的一种&#xff0c;作用是将数据进行抽取&#xff0c;转换&#xff0c;应该是数据中心类型的项目用的比较多&#xff0c;将…

动态sql以及常用的标签

什么是动态sql&#xff1a; 指根据不同的条件生成不同的sql 搭建环境&#xff1a; 建表&#xff1a; create table blog( id varchar(50) not null comment 博客id, title varchar(100) not null comment 博客标题, author varchar(30) not null comment 博客作者, create_ti…

《2023中国开发者调查报告》探索2023中国开发者的技术创新与挑战:AIoT、云原生、国产数据库等领域的发展与前景

&#x1f337;&#x1f341; 博主猫头虎 带您 Go to New World.✨&#x1f341; &#x1f984; 博客首页——猫头虎的博客&#x1f390; &#x1f433;《面试题大全专栏》 文章图文并茂&#x1f995;生动形象&#x1f996;简单易学&#xff01;欢迎大家来踩踩~&#x1f33a; &a…

《Kubernetes故障篇:unable to retrieve OCI runtime error》

一、背景信息 1、环境信息如下&#xff1a; 操作系统K8S版本containerd版本Centos7.6v1.24.12v1.6.12 2、报错信息如下&#xff1a; Warning FailedCreatePodSandBox 106s (x39 over 10m) kubelet (combined from similar events): Failed to create pod sandbox: rpc error: …

HEVC 速率控制(码控)介绍

视频编码速率控制 速率控制&#xff1a; 通过选择一系列编码参数&#xff0c;使得视频编码后的比特率满足所有需要的速率限制&#xff0c;并且使得编码失真尽量小。速率控制属于率失真优化的范畴&#xff0c;速率控制算法的重点是确定与速率相关的量化参数&#xff08;Quantiz…

在OK3588板卡上部署模型实现OCR应用

一、主机模型转换 我们依旧采用FastDeploy来部署应用深度学习模型到OK3588板卡上 进入主机Ubuntu的虚拟环境 conda activate ok3588 安装rknn-toolkit2&#xff08;该工具不能在OK3588板卡上完成模型转换&#xff09; git clone https://github.com/rockchip-linux/rknn-to…

CentOS7系统MBR、GRUB2、内核启动流程报错问题

目录 &#x1f969;Linux启动流程 &#x1f969;MBR修复 &#x1f36d;1、模拟损坏 &#x1f36d;2、重启测试 &#x1f36d;3、修复MBR &#x1f36d;4、测试系统 &#x1f969;GRUB2修复 &#x1f36d;1、模拟损坏 &#x1f36d;2、修复GRUB2 &#x1f36d;3、测试系统 &…

SpringBoot原理分析 | 安全框架:Shiro

&#x1f497;wei_shuo的个人主页 &#x1f4ab;wei_shuo的学习社区 &#x1f310;Hello World &#xff01; Shiro Shiro是一个安全框架&#xff0c;用于认证、授权和管理应用程序的安全性。它提供了一组易于使用的API和工具&#xff0c;可以帮助您轻松地添加安全性到您的应用…

Redis以及Java使用Redis

一、Redis的安装 Redis是一个基于内存的 key-value 结构数据库。 基于内存存储&#xff0c;读写性能高 适合存储热点数据&#xff08;热点商品、资讯、新闻&#xff09; 企业应用广泛 官网&#xff1a;https://redis.io 中文网&#xff1a;https://www.redis.net.cn/ Redis…

.NET网络编程——TCP通信

一、网络编程的基本概念 : 1. 网络 就是将不同区域的电脑连接到一起&#xff0c;组成局域网、城域网或广域网。把分部在不同地理区域的计算机于专门的外部设备用通信线路 互联成一个规模大、功能强的网络系统&#xff0c;从而使众多的计算机可以方便地互相传递信息&#xff0c…

Zabbix分布式监控Web监控

目录 1 概述2 配置 Web 场景2.1 配置步骤2.2 显示 3 Web 场景步骤3.1 创建新的 Web 场景。3.2 定义场景的步骤3.3 保存配置完成的Web 监控场景。 4 Zabbix-Get的使用 1 概述 您可以使用 Zabbix 对多个网站进行可用性方面监控&#xff1a; 要使用 Web 监控&#xff0c;您需要定…

QtC++ 技术分析4 - 流、d-pointer隐式共享以及容器迭代器

目录 QT 中的流文件系统与底层文件操作文件系统类 QFile QTextStreamQDataStreamQLocale 隐式共享与 d-pointer隐式共享d-pointer 在隐式共享中的应用二进制代码兼容d-pointer 模式实现 Qt 容器及迭代器QTL 概述几种常见的迭代器及其对应类型QTL 容器对应迭代器通用算法函子&am…

超全整理,Jmeter性能测试-常用Jmeter第三方插件详解(超细)

目录&#xff1a;导读 前言一、Python编程入门到精通二、接口自动化项目实战三、Web自动化项目实战四、App自动化项目实战五、一线大厂简历六、测试开发DevOps体系七、常用自动化测试工具八、JMeter性能测试九、总结&#xff08;尾部小惊喜&#xff09; 前言 Jmeter作为一个开…

批量插入数据、MVC三层分离

八、批量插入数据 1、使用Statement&#xff08;&#xff09; 2、使用PreparedStatement() 3、使用批量操作API 4、优化 九、MVC三层分离