Awesome Notifications 开源项目教程
项目介绍
Awesome Notifications 是一个用于 Flutter 应用的强大通知插件,支持本地和推送通知。它提供了丰富的自定义选项,包括自定义按钮、图像和声音,以及计划和后台通知功能。该插件旨在简化通知的创建和管理,同时提供高度的灵活性和可扩展性。
项目快速启动
安装依赖
首先,在您的 Flutter 项目的 pubspec.yaml
文件中添加 awesome_notifications
依赖:
dependencies:
flutter:
sdk: flutter
awesome_notifications: ^0.9.3
然后运行 flutter pub get
来安装依赖。
初始化插件
在您的应用启动时初始化 awesome_notifications
:
import 'package:awesome_notifications/awesome_notifications.dart';
void main() {
AwesomeNotifications().initialize(
// 设置通知图标
'resource://drawable/ic_launcher',
[
NotificationChannel(
channelKey: 'basic_channel',
channelName: 'Basic notifications',
channelDescription: 'Notification channel for basic tests',
)
],
);
runApp(MyApp());
}
请求通知权限
在显示通知之前,请求用户权限:
AwesomeNotifications().isNotificationAllowed().then((isAllowed) {
if (!isAllowed) {
AwesomeNotifications().requestPermissionToSendNotifications();
}
});
创建通知
在您的应用中任何地方创建一个通知:
AwesomeNotifications().createNotification(
content: NotificationContent(
id: 1,
channelKey: 'basic_channel',
title: 'Hello World',
body: 'This is my first notification',
),
);
应用案例和最佳实践
自定义按钮通知
您可以创建带有自定义按钮的通知,以提供更多交互选项:
AwesomeNotifications().createNotification(
content: NotificationContent(
id: 2,
channelKey: 'basic_channel',
title: 'Custom Buttons',
body: 'Notification with custom action buttons',
),
actionButtons: [
NotificationActionButton(
key: 'like',
label: 'Like',
),
NotificationActionButton(
key: 'dislike',
label: 'Dislike',
),
],
);
计划通知
您可以设置通知在特定时间触发:
AwesomeNotifications().createNotification(
content: NotificationContent(
id: 3,
channelKey: 'basic_channel',
title: 'Scheduled Notification',
body: 'This notification was scheduled 10 seconds ago',
),
schedule: NotificationCalendar(
second: 10,
allowWhileIdle: true,
),
);
典型生态项目
与 Firebase Cloud Messaging 集成
Awesome Notifications 可以与 Firebase Cloud Messaging (FCM) 集成,以实现远程推送通知。以下是一个简单的集成示例:
- 在 Firebase 控制台中为您的应用启用 FCM。
- 在
pubspec.yaml
中添加firebase_messaging
依赖:
dependencies:
firebase_messaging: ^10.0.0
- 配置 Firebase 并在应用中初始化 FCM:
import 'package:firebase_messaging/firebase_messaging.dart';
void main() {
FirebaseMessaging.instance.requestPermission();
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
AwesomeNotifications().createNotification(
content: NotificationContent(
id: 4,
channelKey: 'basic_channel',
title: message.notification?.title,
body: message.notification?.body,
),
);
});
runApp(MyApp());
}
通过这些步骤,您可以利用 Awesome Notifications 插件在 Flutter 应用中实现强大的通知功能。