Flutter推送通知插件notificare_push_lib的使用
Flutter推送通知插件notificare_push_lib的使用
简介
notificare-push-lib-flutter
是官方提供的Flutter插件,用于在Flutter应用程序中实现Notificare平台的强大智能通知功能。通过该插件,开发者可以轻松集成推送通知、地理位置服务、应用内消息等功能。
完整示例Demo
以下是一个完整的示例代码,展示了如何在Flutter项目中使用 notificare_push_lib
插件来实现推送通知功能。该示例包括了初始化、设备注册、接收通知事件、处理深链接等常见操作。
1. 添加依赖
首先,在 pubspec.yaml
文件中添加 notificare_push_lib
依赖:
dependencies:
flutter:
sdk: flutter
notificare_push_lib: ^<latest_version>
permission_handler: ^<latest_version> # 用于处理权限请求
2. 初始化和配置
在 main.dart
文件中,编写如下代码来初始化 Notificare 并处理各种事件:
import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:io' show Platform;
import 'package:notificare_push_lib/notificare_push_lib.dart';
import 'package:notificare_push_lib/notificare_models.dart';
import 'package:notificare_push_lib/notificare_events.dart';
import 'package:permission_handler/permission_handler.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
[@override](/user/override)
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
final NotificarePushLib notificare = NotificarePushLib();
[@override](/user/override)
void initState() {
super.initState();
// 启动 Notificare
print("Launching...");
notificare.launch();
// 监听 Notificare 事件
notificare.onEventReceived.listen((NotificareEvent event) async {
switch (event.name) {
case "ready": {
// 应用程序已准备好
NotificareReadyEvent readyEvent = event.data as NotificareReadyEvent;
print("Application is Ready: " + readyEvent.application.name!);
// 注册设备以接收推送通知
await notificare.registerForNotifications();
// 注册设备信息(用户ID和用户名)
await _registerDevice("1234567890", "Joel Oliveira");
// 获取收件箱中的通知
List inbox = await _fetchInbox();
// 检查是否启用了远程通知
if (await notificare.isRemoteNotificationsEnabled()) {
print("Remote Notifications Enabled");
}
// 检查是否启用了允许的UI
if (await notificare.isAllowedUIEnabled()) {
print("Allowed UI Enabled");
}
// 如果收件箱中有通知,可以进行处理
if (inbox.isNotEmpty) {
// 可以选择展示收件箱中的第一条通知
// notificare.presentInboxItem(inbox[0]);
// 或者标记为已读
// await notificare.markAsRead(inbox[0]);
}
// 如果是Android设备,请求位置权限并启动位置更新
if (Platform.isAndroid) {
try {
final permission = await Permission.location.request();
if (permission == PermissionStatus.granted) {
notificare.startLocationUpdates().then((_) {
print("location updates started");
});
}
} catch (err) {
// 处理错误
}
} else {
notificare.startLocationUpdates();
}
}
break;
case "urlOpened": {
// 处理打开的URL(深链接)
NotificareUrlOpenedEvent urlOpenedEvent = event.data as NotificareUrlOpenedEvent;
print("URL: " + urlOpenedEvent.url);
}
break;
case "deviceRegistered": {
// 设备已成功注册
NotificareDeviceRegisteredEvent deviceRegisteredEvent = event.data as NotificareDeviceRegisteredEvent;
print("Device: " + deviceRegisteredEvent.device.deviceID!);
// 获取通知设置、标签、首选语言等信息
await _fetchNotificationSettings();
await _fetchTags();
await _addTag("tag_flutter");
await _fetchPreferredLanguage();
}
break;
case "remoteNotificationReceivedInBackground": {
// 在后台接收到远程通知
NotificareRemoteNotificationReceivedInBackgroundEvent remoteNotificationReceivedInBackgroundEvent = event.data as NotificareRemoteNotificationReceivedInBackgroundEvent;
print("Notification: " + remoteNotificationReceivedInBackgroundEvent.notification.message!);
// 展示通知
notificare.presentNotification(remoteNotificationReceivedInBackgroundEvent.notification);
}
break;
case "remoteNotificationReceivedInForeground": {
// 在前台接收到远程通知
NotificareRemoteNotificationReceivedInForegroundEvent remoteNotificationReceivedInForegroundEvent = event.data as NotificareRemoteNotificationReceivedInForegroundEvent;
print("Notification: " + remoteNotificationReceivedInForegroundEvent.notification.message!);
}
break;
// 其他事件处理...
}
});
// 初始化平台状态
initPlatformState();
}
// 平台消息是异步的,因此我们在这里初始化
Future<void> initPlatformState() async {
if (!mounted) return;
}
// 获取通知设置
Future<void> _fetchNotificationSettings() async {
NotificareNotificationSettings settings = await notificare.fetchNotificationSettings();
print("Settings: " + settings.toJson().toString());
}
// 获取首选语言
Future<void> _fetchPreferredLanguage() async {
String? preferredLanguage = await notificare.fetchPreferredLanguage();
print("Preferred Language: " + preferredLanguage.toString());
}
// 注册设备
Future<void> _registerDevice(String userID, String userName) async {
NotificareDevice response = await notificare.registerDevice(userID, userName);
print("Register Device: " + response.toJson().toString());
}
// 获取标签
Future<void> _fetchTags() async {
List tags = await notificare.fetchTags();
print("Tags: " + tags.toString());
}
// 添加标签
Future<void> _addTag(String tag) async {
try {
await notificare.addTag(tag);
print("Added Tag: " + tag);
} catch (e) {
print("Failed to add Tag: " + tag);
}
}
// 获取收件箱中的通知
Future<List> _fetchInbox() async {
List response = await notificare.fetchInbox();
print("Inbox: " + response.toString());
return response;
}
// 获取资产(如图片、视频等)
Future<void> _fetchAssets(String group) async {
List response = await notificare.fetchAssets(group);
print("Assets: " + response.toString());
if (response != null && response.length > 0) {
response.forEach((asset) {
// 处理每个资产
});
}
}
// 检查是否启用了远程通知
Future<void> _isRemoteNotificationsEnabled() async {
bool status = await notificare.isRemoteNotificationsEnabled();
if (status) {
print("Remote Notifications are enabled");
}
}
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Plugin example app'),
),
body: Center(
child: Text('Running...'),
),
),
);
}
}
更多关于Flutter推送通知插件notificare_push_lib的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter推送通知插件notificare_push_lib的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,以下是如何在Flutter项目中使用notificare_push_lib
插件来实现推送通知的一个基本示例。请确保你已经在pubspec.yaml
文件中添加了该插件的依赖,并且已经运行了flutter pub get
。
1. 添加依赖
首先,在你的pubspec.yaml
文件中添加notificare_push_lib
依赖:
dependencies:
flutter:
sdk: flutter
notificare_push_lib: ^最新版本号 # 请替换为最新的版本号
2. 初始化插件
在你的Flutter应用的主文件中(通常是main.dart
),你需要初始化NotificarePushLib
插件。
import 'package:flutter/material.dart';
import 'package:notificare_push_lib/notificare_push_lib.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
// 初始化NotificarePushLib
await NotificarePushLib.initialize(
appId: '你的AppId', // 替换为你的Notificare App ID
appSecret: '你的AppSecret', // 替换为你的Notificare App Secret
onRegister: (token) {
print('Device registered with token: $token');
},
onMessage: (message) {
print('Received message: $message');
// 在这里处理接收到的消息
},
onError: (error) {
print('Error: $error');
},
);
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter Notificare Push Demo'),
),
body: Center(
child: Text('Check console for push notifications logs'),
),
);
}
}
3. 请求通知权限
在iOS和Android上,你需要请求通知权限。这通常在应用的启动流程中完成。以下是一个简单的例子,展示了如何在应用启动时请求通知权限:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
// 检查并请求通知权限
_requestNotificationPermissions();
// 初始化NotificarePushLib(如上所示)
await NotificarePushLib.initialize(
appId: '你的AppId',
appSecret: '你的AppSecret',
onRegister: (token) {
print('Device registered with token: $token');
},
onMessage: (message) {
print('Received message: $message');
// 在这里处理接收到的消息
},
onError: (error) {
print('Error: $error');
},
);
runApp(MyApp());
}
Future<void> _requestNotificationPermissions() async {
if (Platform.isIOS) {
// 对于iOS,使用`flutter_local_notifications`插件来请求权限
// 这里假设你已经添加了`flutter_local_notifications`依赖
final FlutterLocalNotificationsPlugin notificationsPlugin =
FlutterLocalNotificationsPlugin();
var initializationSettingsAndroid = AndroidInitializationSettings('app_icon');
var initializationSettingsIOS = IOSInitializationSettings(
requestAlertPermission: true,
requestBadgePermission: true,
requestSoundPermission: true,
);
var initializationSettings = InitializationSettings(
android: initializationSettingsAndroid,
iOS: initializationSettingsIOS,
);
await notificationsPlugin.initialize(initializationSettings,
onSelectNotification: (String payload) async {
// 用户点击通知时的处理逻辑
print('Notification selected with payload: $payload');
});
await notificationsPlugin.requestPermissions(
alert: true, badge: true, sound: true);
} else if (Platform.isAndroid) {
// 对于Android,NotificarePushLib通常会自动处理权限请求
// 但你也可以在这里添加额外的逻辑
}
}
注意:上面的代码示例中,对于iOS部分使用了flutter_local_notifications
插件来处理权限请求,因为notificare_push_lib
本身可能不直接处理iOS的通知权限请求。确保你已经在pubspec.yaml
中添加了flutter_local_notifications
依赖,并运行了flutter pub get
。
4. 运行应用
现在你可以运行你的Flutter应用,并在控制台中查看设备注册和消息接收的日志。确保你的设备已经连接到开发环境,并且已经启用了开发者模式和USB调试(对于Android设备)。
这个示例提供了一个基本框架,你可以根据自己的需求进一步扩展和自定义。