Flutter本地通知插件flutter_local_notifications_plus的使用
Flutter本地通知插件flutter_local_notifications_plus的使用
Flutter本地通知插件flutter_local_notifications_plus
是一个跨平台插件,用于在不同平台上显示本地通知。以下是该插件的完整示例demo,包括初始化、显示通知、调度通知等。
初始化插件
首先需要创建一个插件实例并进行初始化:
import 'package:flutter_local_notifications_plus/flutter_local_notifications_plus.dart';
import 'package:timezone/timezone.dart' as tz;
import 'package:timezone/data/latest_all.dart' as tz;
final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await _configureLocalTimeZone();
const AndroidInitializationSettings initializationSettingsAndroid =
AndroidInitializationSettings('app_icon');
final DarwinInitializationSettings initializationSettingsDarwin =
DarwinInitializationSettings(
onDidReceiveLocalNotification: onDidReceiveLocalNotification);
final LinuxInitializationSettings initializationSettingsLinux =
LinuxInitializationSettings(defaultActionName: 'Open notification');
final InitializationSettings initializationSettings = InitializationSettings(
android: initializationSettingsAndroid,
iOS: initializationSettingsDarwin,
macOS: initializationSettingsDarwin,
linux: initializationSettingsLinux);
await flutterLocalNotificationsPlugin.initialize(initializationSettings,
onDidReceiveNotificationResponse: onDidReceiveNotificationResponse);
}
void onDidReceiveLocalNotification(
int id, String? title, String? body, String? payload) async {
// 显示对话框,点击OK后跳转到另一个页面
showDialog(
context: context,
builder: (BuildContext context) => CupertinoAlertDialog(
title: Text(title ?? ''),
content: Text(body ?? ''),
actions: [
CupertinoDialogAction(
isDefaultAction: true,
child: Text('Ok'),
onPressed: () async {
Navigator.of(context, rootNavigator: true).pop();
await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => SecondScreen(payload),
),
);
},
)
],
),
);
}
void onDidReceiveNotificationResponse(NotificationResponse notificationResponse) async {
final String? payload = notificationResponse.payload;
if (notificationResponse.payload != null) {
debugPrint('notification payload: $payload');
}
await Navigator.push(
context,
MaterialPageRoute<void>(builder: (context) => SecondScreen(payload)),
);
}
Future<void> _configureLocalTimeZone() async {
tz.initializeTimeZones();
final String? timeZoneName = await FlutterTimezone.getLocalTimezone();
tz.setLocalLocation(tz.getLocation(timeZoneName!));
}
显示通知
接下来展示如何显示一个基本的通知:
Future<void> _showNotification() async {
const AndroidNotificationDetails androidNotificationDetails =
AndroidNotificationDetails('your channel id', 'your channel name',
channelDescription: 'your channel description',
importance: Importance.max,
priority: Priority.high,
ticker: 'ticker');
const NotificationDetails notificationDetails =
NotificationDetails(android: androidNotificationDetails);
await flutterLocalNotificationsPlugin.show(
0, 'plain title', 'plain body', notificationDetails,
payload: 'item x');
}
调度通知
从版本2.0开始,调度通知需要指定时区信息:
Future<void> _zonedScheduleNotification() async {
await flutterLocalNotificationsPlugin.zonedSchedule(
0,
'scheduled title',
'scheduled body',
tz.TZDateTime.now(tz.local).add(const Duration(seconds: 5)),
const NotificationDetails(
android: AndroidNotificationDetails(
'your channel id', 'your channel name',
channelDescription: 'your channel description')),
androidScheduleMode: AndroidScheduleMode.exactAllowWhileIdle,
uiLocalNotificationDateInterpretation:
UILocalNotificationDateInterpretation.absoluteTime);
}
周期性显示通知
可以周期性地显示通知,例如每分钟一次:
Future<void> _repeatNotification() async {
const AndroidNotificationDetails androidNotificationDetails =
AndroidNotificationDetails(
'repeating channel id', 'repeating channel name',
channelDescription: 'repeating description');
const NotificationDetails notificationDetails =
NotificationDetails(android: androidNotificationDetails);
await flutterLocalNotificationsPlugin.periodicallyShow(
0, 'repeating title', 'repeating body', RepeatInterval.everyMinute,
notificationDetails, androidAllowWhileIdle: true);
}
检索待处理的通知请求
可以检索待处理的通知请求列表:
Future<void> _checkPendingNotificationRequests() async {
final List<PendingNotificationRequest> pendingNotificationRequests =
await flutterLocalNotificationsPlugin.pendingNotificationRequests();
return showDialog<void>(
context: context,
builder: (BuildContext context) => AlertDialog(
content: Text('${pendingNotificationRequests.length} pending notification '
'requests'),
actions: <Widget>[
TextButton(
onPressed: () {
Navigator.of(context).pop();
},
child: const Text('OK'),
),
],
),
);
}
取消通知
可以取消特定ID的通知或取消所有通知:
// 取消特定ID的通知
await flutterLocalNotificationsPlugin.cancel(0);
// 取消所有通知
await flutterLocalNotificationsPlugin.cancelAll();
处理应用启动时的通知
获取应用启动时的通知详情:
final NotificationAppLaunchDetails? notificationAppLaunchDetails =
await flutterLocalNotificationsPlugin.getNotificationAppLaunchDetails();
iOS和macOS权限请求
在iOS和macOS上,可以在适当的时间请求通知权限:
Future<void> _requestPermissions() async {
if (Platform.isIOS || Platform.isMacOS) {
await flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<IOSFlutterLocalNotificationsPlugin>()
?.requestPermissions(
alert: true,
badge: true,
sound: true,
);
await flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<MacOSFlutterLocalNotificationsPlugin>()
?.requestPermissions(
alert: true,
badge: true,
sound: true,
);
}
}
更多关于Flutter本地通知插件flutter_local_notifications_plus的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter本地通知插件flutter_local_notifications_plus的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,以下是一个关于如何使用 flutter_local_notifications_plus
插件在 Flutter 应用中发送本地通知的示例代码。这个插件提供了丰富的功能来配置和显示本地通知。
首先,确保你已经在 pubspec.yaml
文件中添加了依赖项:
dependencies:
flutter:
sdk: flutter
flutter_local_notifications: ^10.0.0 # 请检查最新版本号
然后,运行 flutter pub get
来获取依赖项。
接下来,在你的 Flutter 应用中,你需要初始化通知插件,并配置相关的 Android 和 iOS 设置。以下是一个完整的示例:
main.dart
import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Flutter Local Notifications Example'),
),
body: Center(
child: MyHomePage(),
),
),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
@override
void initState() {
super.initState();
var initializationSettingsAndroid =
AndroidInitializationSettings('app_icon'); // 替换为你的应用图标资源名称
var initializationSettingsIOS = IOSInitializationSettings(
requestAlertPermission: true,
requestBadgePermission: true,
requestSoundPermission: true,
);
var initializationSettings = InitializationSettings(
android: initializationSettingsAndroid,
iOS: initializationSettingsIOS,
);
flutterLocalNotificationsPlugin.initialize(initializationSettings,
onSelectNotification: onSelectNotification);
}
Future<void> _showNotification() async {
var androidPlatformChannelSpecifics = AndroidNotificationDetails(
'your_channel_id',
'Your channel name',
'Your channel description',
importance: Importance.max,
priority: Priority.high,
);
var iOSPlatformChannelSpecifics = IOSNotificationDetails();
var platformChannelSpecifics = NotificationDetails(
android: androidPlatformChannelSpecifics,
iOS: iOSPlatformChannelSpecifics,
);
await flutterLocalNotificationsPlugin.show(
0,
'Hello!',
'This is a local notification',
platformChannelSpecifics,
payload: 'item x',
);
}
Future<void> onSelectNotification(String payload) async {
if (payload != null) {
showDialog(
context: context,
builder: (BuildContext context) => CupertinoAlertDialog(
title: Text('Payload'),
content: Text('Payload: $payload'),
actions: <Widget>[
CupertinoDialogAction(
isDefaultAction: true,
child: Text('OK'),
onPressed: () {
Navigator.of(context).pop();
},
),
],
),
);
}
}
@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: _showNotification,
child: Text('Show Notification'),
);
}
}
Android 配置
在 android/app/src/main/AndroidManifest.xml
中,确保你有权限请求:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.VIBRATE" />
并添加一个 meta-data
标签来指定应用图标:
<meta-data
android:name="com.dexterous.flutterlocalnotifications.default_notification_channel_id"
android:value="your_channel_id"/> <!-- 确保与代码中的 channel_id 一致 -->
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="@string/default_notification_channel_id"/>
在 android/app/src/main/res/drawable
文件夹中,确保你有一个名为 app_icon
的图标文件(或替换为你自己的图标名称)。
iOS 配置
在 ios/Runner/Info.plist
中,添加以下权限请求:
<key>UIBackgroundModes</key>
<array>
<string>remote-notification</string>
</array>
<key>UNNotificationBreakthroughPriority</key>
<integer>1</integer>
在 ios/Runner/AppDelegate.swift
或 AppDelegate.m
中,根据语言选择添加以下内容:
Swift:
import UserNotifications
import FlutterLocalNotificationsPlugin
@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
GeneratedPluginRegistrant.register(with: self)
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .badge, .sound]) { granted, error in
if let error = error {
print("Notification setup failed: \(error.localizedDescription)")
} else if granted {
DispatchQueue.main.async {
application.registerForRemoteNotifications()
}
}
}
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}
Objective-C:
#import <UserNotifications/UserNotifications.h>
#import <FlutterLocalNotificationsPlugin/FlutterLocalNotificationsPlugin.h>
@interface AppDelegate (UNUserNotificationCenterDelegate)
@end
@implementation AppDelegate (UNUserNotificationCenterDelegate)
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[GeneratedPluginRegistrant registerWithRegistry:self];
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
[center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert | UNAuthorizationOptionBadge | UNAuthorizationOptionSound) completionHandler:^(BOOL granted, NSError * _Nullable error) {
if (!error) {
dispatch_async(dispatch_get_main_queue(), ^{
[application registerForRemoteNotifications];
});
}
}];
return [super application:application didFinishLaunchingWithOptions:launchOptions];
}
@end
这个示例代码展示了如何初始化 flutter_local_notifications_plus
插件,配置 Android 和 iOS 的必要设置,以及发送一个简单的本地通知。你可以根据需要进一步自定义通知的细节和行为。