Flutter使用flutter_local_notifications插件实现手机定时推送本地通知
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
// 初始化本地通知插件
final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
// 显示本地通知的方法
Future<void> showNotification() async {
// 定义通知的资源
const AndroidNotificationDetails androidNotificationDetails =
AndroidNotificationDetails('channel id', 'channel name', 'channel description',
importance: Importance.max, priority: Priority.high);
const NotificationDetails notificationDetails =
NotificationDetails(android: androidNotificationDetails);
// 显示通知
await flutterLocalNotificationsPlugin.show(
, 'New Message', 'You have a new message', notificationDetails);
}
// 在initState中配置本地通知
@override
void initState() {
super.initState();
// 配置本地通知
flutterLocalNotificationsPlugin.initialize(InitializationSettings(
android: AndroidInitializationSettings('app_icon'),
), onSelectNotification: (String payload) {
// 点击通知后的回调
print('payload: $payload');
});
}
这段代码展示了如何在Flutter应用中使用flutter_local_notifications
插件来初始化和显示本地通知。首先,创建了FlutterLocalNotificationsPlugin
的实例,然后定义了Android通知的细节。在initState
中,我们调用initialize
方法来配置通知。最后,我们实现了一个showNotification
方法来显示一个本地通知。
评论已关闭