Flutter通知服务插件notification_service的使用
Flutter通知服务插件notification_service的使用
本示例展示了如何在Flutter项目中使用Firebase Cloud Messaging(FCM)来实现推送通知。
如何在你的项目中实现Firebase:
-
创建Flutter项目
打开终端并运行以下命令:
flutter create notification_example cd notification_example
-
在Firebase控制台创建项目
访问Firebase控制台并创建一个新的项目。
-
完成Android和iOS平台的Firebase项目设置
在Firebase控制台中,下载
google-services.json
文件,并将其放置到项目的android/app
目录下。 对于iOS,需要进行一些Xcode配置。你可以参考这里的指南。 -
在
pubspec.yaml
中添加依赖在
pubspec.yaml
文件中添加以下依赖项:dev_dependencies: flutter_test: sdk: flutter firebase_messaging: ^14.6.1 flutter_local_notifications: ^14.1.0 firebase_core: ^2.13.0
-
配置AndroidManifest.xml
打开
android/app/src/main/AndroidManifest.xml
文件,并在<activity>
标签内添加以下内容:<activity <intent-filter> <action android:name="FLUTTER_NOTIFICATION_CLICK" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity> <application <meta-data android:name="com.google.firebase.messaging.default_notification_channel_id" android:value="high_importance_channel" /> <meta-data android:name="com.google.firebase.messaging.default_notification_icon" android:resource="@mipmap/ic_launcher" /> <meta-data android:name="com.google.firebase.messaging.default_notification_color" android:resource="@color/notification_color" /> </application>
-
在
app/build.gradle
中添加插件打开
android/app/build.gradle
文件,并在最后一行添加以下内容:apply plugin: 'com.google.gms.google-services'
-
在
android/build.gradle
中添加依赖打开
android/build.gradle
文件,并在dependencies
块中添加以下内容:dependencies { classpath 'com.google.gms:google-services:4.3.8' }
-
编写通知服务插件代码
创建一个名为
notification_service.dart
的文件,并添加以下代码:import 'package:flutter/material.dart'; import 'package:firebase_messaging/firebase_messaging.dart'; import 'package:flutter_local_notifications/flutter_local_notifications.dart'; // 初始化FirebaseMessaging final FirebaseMessaging _firebaseMessaging = FirebaseMessaging.instance; // 初始化FlutterLocalNotificationsPlugin final FlutterLocalNotificationsPlugin _flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin(); void main() async { WidgetsFlutterBinding.ensureInitialized(); // 配置本地通知插件 const AndroidInitializationSettings initializationSettingsAndroid = AndroidInitializationSettings('@mipmap/ic_launcher'); final InitializationSettings initializationSettings = InitializationSettings( android: initializationSettingsAndroid, ); await _flutterLocalNotificationsPlugin.initialize(initializationSettings); // 请求权限 NotificationSettings settings = await _firebaseMessaging.requestPermission( alert: true, badge: true, sound: true, provisional: false, ); // 监听消息 FirebaseMessaging.onMessage.listen((RemoteMessage message) { RemoteNotification? notification = message.notification; AndroidNotification? android = message.notification?.android; if (notification != null && android != null) { _flutterLocalNotificationsPlugin.show( notification.hashCode, notification.title, notification.body, NotificationDetails( android: AndroidNotificationDetails( 'high_importance_channel', // 通道ID 'High Importance Notifications', // 通道名称 importance: Importance.max, priority: Priority.high, ), ), ); } }); runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: Text('Flutter Notification Example')), body: Center(child: Text('Check your notifications!')), ), ); } }
更多关于Flutter通知服务插件notification_service的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter通知服务插件notification_service的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
在Flutter中,notification_service
是一个用于管理和显示通知的插件。虽然目前没有官方或广泛认可的插件名为 notification_service
,但通常我们会使用 flutter_local_notifications
插件来实现通知功能。以下是如何使用 flutter_local_notifications
插件来实现通知服务的步骤。
1. 添加依赖
首先,在 pubspec.yaml
文件中添加 flutter_local_notifications
插件的依赖:
dependencies:
flutter:
sdk: flutter
flutter_local_notifications: ^14.0.0
然后运行 flutter pub get
来获取依赖。
2. 初始化插件
在你的 Dart 文件中初始化 flutter_local_notifications
插件。
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
void initializeNotifications() async {
const AndroidInitializationSettings initializationSettingsAndroid =
AndroidInitializationSettings('@mipmap/ic_launcher');
const InitializationSettings initializationSettings = InitializationSettings(
android: initializationSettingsAndroid,
);
await flutterLocalNotificationsPlugin.initialize(initializationSettings);
}
3. 显示通知
你可以使用 show
方法来显示通知。
void showNotification() async {
const AndroidNotificationDetails androidPlatformChannelSpecifics =
AndroidNotificationDetails(
'your channel id',
'your channel name',
importance: Importance.max,
priority: Priority.high,
);
const NotificationDetails platformChannelSpecifics =
NotificationDetails(android: androidPlatformChannelSpecifics);
await flutterLocalNotificationsPlugin.show(
0,
'Notification Title',
'This is the notification body',
platformChannelSpecifics,
payload: 'item x',
);
}
4. 处理通知点击事件
你可以通过 initialize
方法中的 onSelectNotification
回调来处理通知的点击事件。
void initializeNotifications() async {
const AndroidInitializationSettings initializationSettingsAndroid =
AndroidInitializationSettings('@mipmap/ic_launcher');
const InitializationSettings initializationSettings = InitializationSettings(
android: initializationSettingsAndroid,
);
await flutterLocalNotificationsPlugin.initialize(initializationSettings,
onSelectNotification: (String? payload) async {
if (payload != null) {
print('Notification payload: $payload');
}
});
}
5. 调度通知
你还可以使用 zonedSchedule
方法来调度通知。
void scheduleNotification() async {
const AndroidNotificationDetails androidPlatformChannelSpecifics =
AndroidNotificationDetails(
'your channel id',
'your channel name',
importance: Importance.max,
priority: Priority.high,
);
const NotificationDetails platformChannelSpecifics =
NotificationDetails(android: androidPlatformChannelSpecifics);
await flutterLocalNotificationsPlugin.zonedSchedule(
0,
'Scheduled Notification',
'This is a scheduled notification',
tz.TZDateTime.now(tz.local).add(const Duration(seconds: 5)),
platformChannelSpecifics,
androidAllowWhileIdle: true,
uiLocalNotificationDateInterpretation:
UILocalNotificationDateInterpretation.absoluteTime,
);
}
6. 取消通知
你可以使用 cancel
方法来取消通知。
void cancelNotification(int notificationId) async {
await flutterLocalNotificationsPlugin.cancel(notificationId);
}
7. 取消所有通知
你可以使用 cancelAll
方法来取消所有通知。
void cancelAllNotifications() async {
await flutterLocalNotificationsPlugin.cancelAll();
}
8. 处理后台通知
如果需要处理后台通知,你需要在 AndroidManifest.xml
文件中配置后台服务。
<service
android:name="com.dexterous.flutterlocalnotifications.ScheduledNotificationBootReceiver"
android:enabled="true"
android:exported="true" />
9. 处理通知渠道
Android 8.0 (API level 26) 及以上版本需要创建通知渠道。
void createNotificationChannel() async {
const AndroidNotificationChannel channel = AndroidNotificationChannel(
'high_importance_channel', // id
'High Importance Notifications', // title
importance: Importance.high,
);
await flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin>()
?.createNotificationChannel(channel);
}
10. 完整示例
以下是一个完整的示例:
import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:timezone/data/latest.dart' as tz;
import 'package:timezone/timezone.dart' as tz;
void main() async {
WidgetsFlutterBinding.ensureInitialized();
tz.initializeTimeZones();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
home: NotificationExample(),
);
}
}
class NotificationExample extends StatefulWidget {
[@override](/user/override)
_NotificationExampleState createState() => _NotificationExampleState();
}
class _NotificationExampleState extends State<NotificationExample> {
final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
[@override](/user/override)
void initState() {
super.initState();
initializeNotifications();
}
void initializeNotifications() async {
const AndroidInitializationSettings initializationSettingsAndroid =
AndroidInitializationSettings('@mipmap/ic_launcher');
const InitializationSettings initializationSettings = InitializationSettings(
android: initializationSettingsAndroid,
);
await flutterLocalNotificationsPlugin.initialize(initializationSettings,
onSelectNotification: (String? payload) async {
if (payload != null) {
print('Notification payload: $payload');
}
});
}
void showNotification() async {
const AndroidNotificationDetails androidPlatformChannelSpecifics =
AndroidNotificationDetails(
'your channel id',
'your channel name',
importance: Importance.max,
priority: Priority.high,
);
const NotificationDetails platformChannelSpecifics =
NotificationDetails(android: androidPlatformChannelSpecifics);
await flutterLocalNotificationsPlugin.show(
0,
'Notification Title',
'This is the notification body',
platformChannelSpecifics,
payload: 'item x',
);
}
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Notification Example'),
),
body: Center(
child: ElevatedButton(
onPressed: showNotification,
child: Text('Show Notification'),
),
),
);
}
}