flutter如何在应用处于后台时使用flutter_local_notifications显示通知
在Flutter应用中,当应用处于后台时,如何正确使用flutter_local_notifications插件显示通知?我尝试在后台任务中触发通知,但有时无法正常显示。是否需要额外配置或权限?能否提供一个在后台状态稳定触发通知的完整示例代码?
2 回复
在 Flutter 应用处于后台时,可以使用 flutter_local_notifications 显示通知,配置步骤如下:
-
配置 Android(AndroidManifest.xml):
- 添加权限:
<uses-permission android:name="android.permission.VIBRATE" /> <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/> - 在
<application>内注册服务:<service android:name="com.dexterous.flutterlocalnotifications.ScheduledNotificationService"/>
- 添加权限:
-
配置 iOS(AppDelegate.swift):
- 添加通知权限请求:
if #available(iOS 10.0, *) { UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in } }
- 添加通知权限请求:
-
Flutter 代码:
- 初始化插件:
final FlutterLocalNotificationsPlugin notifications = FlutterLocalNotificationsPlugin(); // 设置初始化设置(AndroidChannel 等) - 使用
zonedSchedule安排后台通知:notifications.zonedSchedule( id, '标题', '内容', tz.TZDateTime.now(tz.local).add(Duration(seconds: 5)), const NotificationDetails(...), uiLocalNotificationDateInterpretation: UILocalNotificationDateInterpretation.absoluteTime, androidAllowWhileIdle: true, );
- 初始化插件:
注意:确保应用已获取通知权限(requestPermissions),且测试时需真机运行。
更多关于flutter如何在应用处于后台时使用flutter_local_notifications显示通知的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
在Flutter应用处于后台时,可以使用flutter_local_notifications插件配合Firebase Messaging或后台任务来显示通知。以下是实现步骤:
1. 添加依赖
在 pubspec.yaml 中添加:
dependencies:
flutter_local_notifications: ^16.3.0
firebase_messaging: ^14.7.9 # 可选,用于后台消息处理
2. 配置通知初始化
在 main.dart 中初始化通知插件:
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
void main() async {
WidgetsFlutterBinding.ensureInitialized();
// 初始化通知设置
const AndroidInitializationSettings androidSettings =
AndroidInitializationSettings('@mipmap/ic_launcher');
const DarwinInitializationSettings iosSettings =
DarwinInitializationSettings();
const InitializationSettings initSettings = InitializationSettings(
android: androidSettings,
iOS: iosSettings,
);
await flutterLocalNotificationsPlugin.initialize(initSettings);
runApp(MyApp());
}
3. 后台消息处理(使用Firebase Messaging)
如果使用Firebase处理后台消息,需配置后台处理函数:
// 在 main.dart 或单独文件中
@pragma('vm:entry-point')
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
await showNotification(
title: message.notification?.title ?? 'Background Notification',
body: message.notification?.body ?? 'New message received',
);
}
Future<void> showNotification({required String title, required String body}) async {
const AndroidNotificationDetails androidDetails = AndroidNotificationDetails(
'channel_id',
'Channel Name',
importance: Importance.max,
priority: Priority.high,
);
const DarwinNotificationDetails iosDetails = DarwinNotificationDetails();
const NotificationDetails details = NotificationDetails(
android: androidDetails,
iOS: iosDetails,
);
await flutterLocalNotificationsPlugin.show(
0, // 通知ID
title,
body,
details,
);
}
4. 配置Firebase(可选)
在 android/app/src/main/AndroidManifest.xml 中添加:
<service
android:name="io.flutter.plugins.firebase.messaging.FlutterFirebaseMessagingBackgroundService"
android:exported="false" />
5. 请求权限
在应用启动时请求通知权限:
// 在初始化后调用
await flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin>()
?.requestPermission();
// iOS需额外配置Info.plist
关键说明:
- 后台触发:通过Firebase Messaging的
onBackgroundMessage或系统后台任务触发通知 - 平台差异:Android需配置通知渠道,iOS需在
Info.plist添加权限描述 - 确保正确处理通知点击事件,通过
onSelectNotification回调处理
此方案可在应用后台运行时可靠地显示本地通知。

