Flutter本地通知插件simple_android_notification的使用
Flutter本地通知插件simple_android_notification的使用
本项目是一个新的Flutter插件项目,专门用于实现Android和/或iOS平台上的本地通知功能。
开始使用
这个项目是Flutter插件包的起点。要开始使用Flutter进行开发,可以查看官方文档,其中包含教程、示例、移动开发指南以及完整的API参考。
示例代码
以下是使用simple_android_notification
插件的基本示例代码:
// 忽略未使用的导入
import 'dart:developer';
import 'package:flutter/material.dart';
import 'package:simple_android_notification/models/notification_data.dart';
import 'dart:async';
import 'package:simple_android_notification/simple_android_notification.dart';
import 'package:simple_android_notification_example/channel_screen.dart';
import 'package:simple_android_notification_example/listener_screen.dart';
import 'package:simple_android_notification_example/widgets/input_box.dart';
final plugin = SimpleAndroidNotification();
void main() {
runApp(const MaterialApp(
title: "Simple Android Notification",
debugShowCheckedModeBanner: false,
home: HomeScreen(),
));
}
class HomeScreen extends StatefulWidget {
const HomeScreen({super.key});
[@override](/user/override)
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
String? _payload;
bool _notificationPermission = false;
bool _notificationListenerPermission = false;
[@override](/user/override)
void initState() {
super.initState();
getPayload();
hasNotificationPermission();
hasListenerPermission();
}
[@override](/user/override)
Widget build(BuildContext context) {
ThemeData theme = Theme.of(context);
return Scaffold(
appBar: AppBar(
title: const Text('插件示例应用'),
),
body: ListView(
padding: const EdgeInsets.symmetric(horizontal: 16.0),
children: [
Center(child: Text('Payload: $_payload')),
Center(
child: Text(
"如果非空,则应用通过点击通知打开",
style: theme.textTheme.labelSmall,
)),
const Divider(),
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
"通道特性",
style: theme.textTheme.titleMedium,
textAlign: TextAlign.center,
),
),
ElevatedButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ChannelScreen(plugin: plugin)),
);
},
child: const Text("打开通道列表屏幕"),
),
const Divider(),
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
"通知特性",
style: theme.textTheme.titleMedium,
textAlign: TextAlign.center,
),
),
Center(
child: Text('hasNotificationPermission : $_notificationPermission'),
),
ElevatedButton(
onPressed: hasNotificationPermission,
child: const Text('检查通知权限'),
),
ElevatedButton(
onPressed: requestNotificationPermission,
child: const Text('请求通知权限'),
),
ElevatedButton(
onPressed: () => showNotificationDialog(context),
child: const Text('显示通知'),
),
const Divider(),
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
"通知监听器特性",
style: theme.textTheme.titleMedium,
textAlign: TextAlign.center,
),
),
Center(
child: Text(
'hasListenerPermission : $_notificationListenerPermission'),
),
ElevatedButton(
onPressed: hasListenerPermission,
child: const Text('检查通知监听器权限'),
),
ElevatedButton(
onPressed: openListenerPermissionSetting,
child: const Text('打开监听器权限设置'),
),
ElevatedButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ListenerScreen(plugin: plugin),
),
);
},
child: const Text("打开监听器屏幕"),
),
],
),
);
}
Future<void> getPayload() async {
var payload = await plugin.getPayload();
setState(() => _payload = payload);
}
Future<void> hasNotificationPermission() async {
bool permission = await plugin.hasNotificationPermission();
setState(() => _notificationPermission = permission);
}
Future<void> requestNotificationPermission() async {
await plugin.requestNotificationPermission();
}
void showNotificationDialog(BuildContext context) {
final TextEditingController idController = TextEditingController();
final TextEditingController titleController = TextEditingController();
final TextEditingController contentController = TextEditingController();
final TextEditingController payloadController = TextEditingController();
final formKey = GlobalKey<FormState>();
showDialog(
context: context,
builder: (BuildContext context) {
return Dialog(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Form(
key: formKey,
child: ListView(
children: [
InputBox(
maxLength: 50,
controller: idController,
label: "通道ID",
),
InputBox(
maxLength: 30,
controller: titleController,
label: "标题",
),
InputBox(
maxLength: 60,
controller: contentController,
label: "内容",
),
InputBox(
maxLength: 30,
controller: payloadController,
action: TextInputAction.done,
label: "负载",
activeValidator: false,
),
const SizedBox(height: 10),
ElevatedButton(
onPressed: () async {
if (formKey.currentState!.validate()) {
var notificationData = NotificationData(
channelId: idController.text,
title: titleController.text,
content: contentController.text,
payload: payloadController.text);
showNotification(notificationData);
}
},
child: const Text("发送通知"),
),
ElevatedButton(
onPressed: () => Navigator.pop(context),
child: const Text("取消"),
),
],
),
),
),
);
},
);
}
Future<void> showNotification(NotificationData notificationData) async {
Navigator.of(context).pop();
await plugin.showNotification(notificationData);
}
Future<void> hasListenerPermission() async {
bool permission = await plugin.hasListenerPermission();
setState(() => _notificationListenerPermission = permission);
}
Future<void> openListenerPermissionSetting() async {
await plugin.openListenerPermissionSetting();
}
}
更多关于Flutter本地通知插件simple_android_notification的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter本地通知插件simple_android_notification的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
simple_android_notification
是一个用于在 Android 平台上发送本地通知的 Flutter 插件。它提供了一个简单易用的 API,允许开发者在 Flutter 应用中轻松地创建和显示通知。以下是如何使用 simple_android_notification
插件的基本步骤。
1. 添加依赖
首先,你需要在 pubspec.yaml
文件中添加 simple_android_notification
插件的依赖:
dependencies:
flutter:
sdk: flutter
simple_android_notification: ^1.0.0 # 请检查最新版本
然后运行 flutter pub get
来安装依赖。
2. 导入插件
在你的 Dart 文件中导入 simple_android_notification
插件:
import 'package:simple_android_notification/simple_android_notification.dart';
3. 初始化插件
在使用插件之前,通常需要对其进行初始化。你可以在 main
函数或 initState
中进行初始化:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await SimpleAndroidNotification.initialize();
runApp(MyApp());
}
4. 创建和显示通知
使用 SimpleAndroidNotification
类来创建和显示通知。以下是一个简单的示例:
void showNotification() async {
await SimpleAndroidNotification.show(
id: 1, // 通知的唯一ID
title: 'My Notification Title', // 通知标题
body: 'This is the body of the notification.', // 通知内容
payload: 'notification_payload', // 可选:通知的附加数据
);
}
5. 处理通知点击事件
为了处理用户点击通知的事件,你可以在 MaterialApp
或 CupertinoApp
的 onGenerateRoute
或 navigatorKey
中监听通知的点击事件。
final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await SimpleAndroidNotification.initialize();
SimpleAndroidNotification.onNotificationClick.listen((payload) {
// 处理通知点击事件
print('Notification clicked with payload: $payload');
navigatorKey.currentState?.pushNamed('/notification');
});
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
navigatorKey: navigatorKey,
initialRoute: '/',
routes: {
'/': (context) => HomeScreen(),
'/notification': (context) => NotificationScreen(),
},
);
}
}
6. 自定义通知
你可以通过传递更多参数来自定义通知的外观和行为,例如设置通知的图标、声音、振动等。
void showCustomNotification() async {
await SimpleAndroidNotification.show(
id: 2,
title: 'Custom Notification',
body: 'This is a custom notification.',
payload: 'custom_payload',
icon: 'ic_notification', // 通知图标(位于 res/drawable 目录下)
sound: 'notification_sound.mp3', // 通知声音(位于 res/raw 目录下)
vibrate: true, // 是否振动
priority: SimpleAndroidNotification.priorityHigh, // 通知优先级
);
}
7. 取消通知
你可以通过通知的 ID 来取消已显示的通知:
void cancelNotification() async {
await SimpleAndroidNotification.cancel(1); // 取消ID为1的通知
}