Flutter Windows通知管理插件windows_notification的使用
Flutter Windows通知管理插件windows_notification
的使用
windows_notification
是一个用于在Windows上通过Flutter发送通知的库。它提供了丰富的功能,如使用预定义模板或自定义模板发送通知、接收已发送的通知事件、从Windows Action Center删除所有或特定组的通知、为通知添加深度链接等。
功能特性
- 发送预定义模板的通知:利用插件自带的三种模板快速构建并发送通知。
- 发送自定义模板的通知:根据需求设计自己的通知模板并发送。
- 接收发送的通知事件:能够监听和响应用户与通知的交互。
- 清除Action Center中的通知:可以按需删除所有由你发送的通知或特定分组下的通知。
- 添加深度链接到通知:使点击通知时能导向应用内的指定页面或其他URL。
使用方法
发送带有插件模板的通知
import 'package:windows_notification/notification_message.dart';
import 'package:windows_notification/windows_notification.dart';
final _winNotifyPlugin = WindowsNotification(applicationId: "your_application_id");
// 创建一个新的NotificationMessage实例,包括id, title, body 和 图片路径
NotificationMessage message = NotificationMessage.fromPluginTemplate(
"test1",
"Title",
"Body",
largeImage: file_path,
image: file_path
);
// 显示通知
_winNotifyPlugin.showNotificationPluginTemplate(message);
发送带有自定义模板的通知
const String template = '''
<toast activationType="protocol">
<visual>
<binding template="ToastGeneric">
<text>Weather app</text>
<text>Expect rain today.</text>
...
</binding>
</visual>
</toast>
''';
NotificationMessage message = NotificationMessage.fromCustomTemplate("notificationid_1", group: "weather_group");
_winNotifyPlugin.showNotificationCustomTemplate(message, template);
删除Action Center中的通知
-
删除所有通知:
_winNotifyPlugin.clearNotificationHistory();
-
删除特定组的通知:
_winNotifyPlugin.removeNotificationGroup("groupname");
-
删除单个通知(需要提供ID和组名):
_winNotifyPlugin.removeNotificationId("notificationid", "groupname");
处理事件和参数
为了接收你的通知事件,你需要初始化回调函数:
_winNotifyPlugin.initNotificationCallBack((NotificationMessage data, EventType eventType, String? arguments) {
// 在这里处理事件逻辑
});
添加启动选项
你可以通过设置launch
属性来实现深度链接功能,例如:
NotificationMessage message = NotificationMessage.fromPluginTemplate(
"test1",
"You Win",
"Tap to receive a gift",
launch: "my-app-schame://page1"
);
_winNotifyPlugin.showNotificationPluginTemplate(message);
这将使得当用户点击通知时,会被重定向到应用程序内的某个页面或者外部链接。
示例代码
下面是一个完整的示例程序,展示了如何使用windows_notification
插件的各种功能:
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:windows_notification/notification_message.dart';
import 'package:windows_notification/windows_notification.dart';
import 'package:path_provider/path_provider.dart';
import 'package:http/http.dart' as http;
void main() {
runApp(const MaterialApp(
home: MyApp(),
color: Colors.red,
themeMode: ThemeMode.light,
));
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
Future<String> getImageBytes(String url) async {
final supportDir = await getApplicationSupportDirectory();
final cl = http.Client();
final resp = await cl.get(Uri.parse(url));
final bytes = resp.bodyBytes;
final imageFile = File("${supportDir.path}/${DateTime.now().millisecond}.png");
await imageFile.create();
await imageFile.writeAsBytes(bytes);
return imageFile.path;
}
void showWithLargeImage() async {
const String url = "https://user-images.githubusercontent.com/56779182/205485419-4303fdca-9f96-48e8-b6af-6f0df2ce8419.png";
final imageDir = await getImageBytes(url);
NotificationMessage message = NotificationMessage.fromPluginTemplate(
"moon",
"fly to the moon",
"we are ready!",
largeImage: imageDir,
launch: "https://en.wikipedia.org/wiki/Japanese_language",
);
_winNotifyPlugin.showNotificationPluginTemplate(message);
}
void showWithSmallImage() async {
const String url = "https://www.wikipedia.org/portal/wikipedia.org/assets/img/Wikipedia-logo-v2@1.5x.png";
final imageDir = await getImageBytes(url);
NotificationMessage message = NotificationMessage.fromPluginTemplate(
"Japanese language", "Japanese language", "how to read",
image: imageDir,
launch: "https://en.wikipedia.org/wiki/Japanese_language");
_winNotifyPlugin.showNotificationPluginTemplate(message);
}
void showWithLargeAndSmalImage() async {
const String url = "https://www.wikipedia.org/portal/wikipedia.org/assets/img/Wikipedia-logo-v2@1.5x.png";
final imageDir = await getImageBytes(url);
NotificationMessage message = NotificationMessage.fromPluginTemplate(
"Japanese language", "Japanese language", "how to read",
image: imageDir,
launch: "https://en.wikipedia.org/wiki/Japanese_language",
largeImage: imageDir);
_winNotifyPlugin.showNotificationPluginTemplate(message);
}
void showAlarm() {
NotificationMessage message = NotificationMessage.fromCustomTemplate("test1", group: "jj");
_winNotifyPlugin.showNotificationCustomTemplate(message, alarmtTemplate);
}
void showMeetingTemplate() {
NotificationMessage message = NotificationMessage.fromCustomTemplate("test1", group: "jj");
_winNotifyPlugin.showNotificationCustomTemplate(message, meetingTemplate);
}
final _winNotifyPlugin = WindowsNotification(applicationId: r"your_application_id");
@override
void initState() {
_winNotifyPlugin.initNotificationCallBack((s) {
print(s.arguments);
print(s.userInput);
print(s.eventType);
});
super.initState();
}
void sendWithPluginTemplate() {
NotificationMessage message = NotificationMessage.fromPluginTemplate(
"test1", "TEXT", "TEXT",
image: r"C:\in_work\mrt_logo\large.png",
payload: {"action": "open_center"});
_winNotifyPlugin.showNotificationPluginTemplate(message);
}
void sendMyOwnTemplate() {
const String template = '''
<toast launch='conversationId=9813' activationType="background">
<visual>
<binding template='ToastGeneric'>
<text>Some text</text>
</binding>
</visual>
<actions>
<action content='Archive' arguments='action:archive'/>
</actions>
</toast>
''';
NotificationMessage message = NotificationMessage.fromCustomTemplate("test1", group: "jj");
_winNotifyPlugin.showNotificationCustomTemplate(message, template);
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Plugin example app'),
),
body: SizedBox(
width: MediaQuery.of(context).size.width,
child: CustomScrollView(
slivers: [
SliverPadding(
padding: const EdgeInsets.all(25),
sliver: SliverToBoxAdapter(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
onPressed: () {
sendMyOwnTemplate();
},
child: const Text("Send simple notification with custom template and simple action")),
const SizedBox(height: 15),
ElevatedButton(
onPressed: () {
sendWithPluginTemplate();
},
child: const Text("Send Simple notification with title body and small image")),
const SizedBox(height: 15),
ElevatedButton(
onPressed: () {
_winNotifyPlugin.clearNotificationHistory();
},
child: const Text("Clear action center notification")),
const SizedBox(height: 15),
ElevatedButton(
onPressed: () {
_winNotifyPlugin.removeNotificationGroup("jj");
},
child: const Text("Clear group notification")),
const SizedBox(height: 15),
ElevatedButton(
onPressed: () {
_winNotifyPlugin.removeNotificationId("test1", "jj");
},
child: const Text("Remove single notification")),
const SizedBox(height: 8),
ElevatedButton(
onPressed: () {
showAlarm();
},
child: const Text("show alarm with custom template userInputs and action")),
const SizedBox(height: 8),
ElevatedButton(
onPressed: () {
showWithLargeImage();
},
child: const Text("show with large image and lunch uri")),
const SizedBox(height: 8),
ElevatedButton(
onPressed: () {
showWithSmallImage();
},
child: const Text("show with small image and lunch uri")),
const SizedBox(height: 8),
ElevatedButton(
onPressed: () {
showWithLargeAndSmalImage();
},
child: const Text("show with large and small image and lunch uri")),
const SizedBox(height: 8),
ElevatedButton(
onPressed: () {
showMeetingTemplate();
},
child: const Text("meeting template with action and inputs")),
],
),
),
)
],
)),
),
);
}
}
请确保替换your_application_id
为实际的应用程序ID,并根据需要调整其他参数。此外,如果要使用图像,请保证提供的图片URL有效且可访问。这个例子演示了如何创建不同类型的Windows通知,以及如何管理和响应这些通知。
更多关于Flutter Windows通知管理插件windows_notification的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter Windows通知管理插件windows_notification的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,下面是一个关于如何在Flutter项目中使用windows_notification
插件来管理Windows通知的示例代码。这个插件允许你在Windows平台上发送本地通知。
首先,确保你已经在pubspec.yaml
文件中添加了windows_notification
依赖:
dependencies:
flutter:
sdk: flutter
windows_notification: ^x.y.z # 请将x.y.z替换为当前最新版本号
然后,运行flutter pub get
来安装依赖。
接下来,配置你的Flutter项目以支持Windows平台(如果还没有配置的话)。运行以下命令:
flutter config --enable-windows-desktop
flutter create .
确保你的CMakeLists.txt
和windows
文件夹已经正确生成。
然后,在你的Flutter项目中,你可以按照以下步骤使用windows_notification
插件:
- 导入插件:
在你的Dart文件中(例如main.dart
),导入windows_notification
插件:
import 'package:flutter/material.dart';
import 'package:windows_notification/windows_notification.dart';
- 发送通知:
创建一个函数来发送通知。以下是一个简单的例子:
void sendNotification() async {
try {
// 创建通知内容
var notification = WindowsNotification()
..title = 'Hello'
..body = 'This is a test notification from Flutter!'
..icon = 'path/to/your/icon.ico'; // 可选,设置通知图标
// 发送通知
await WindowsNotificationManager.show(notification);
print('Notification sent successfully');
} catch (e) {
print('Failed to send notification: $e');
}
}
- 在UI中调用发送通知的函数:
例如,你可以在按钮点击事件中调用这个函数:
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Windows Notification Example'),
),
body: Center(
child: ElevatedButton(
onPressed: sendNotification,
child: Text('Send Notification'),
),
),
),
);
}
}
- 运行应用:
确保你的Flutter项目已经配置好Windows平台支持,然后运行以下命令来启动应用:
flutter run -d windows
点击按钮后,你应该会在Windows系统上看到一个本地通知。
请注意,path/to/your/icon.ico
需要替换为你实际图标文件的路径。图标文件应该是一个有效的ICO文件,并且位于你的项目目录中或者你可以提供一个完整的文件路径。
这个示例展示了如何使用windows_notification
插件在Flutter Windows应用中发送本地通知。根据你的需求,你可以进一步定制通知的内容和外观。