Flutter:flutter_local_notifications——消息推送的学习
在Flutter中,flutter_local_notifications
插件可以用来处理本地通知,这对于学习如何在应用中实现消息推送是一个很好的资源。以下是一个简单的例子,展示如何设置和使用flutter_local_notifications
插件。
首先,在你的pubspec.yaml
文件中添加flutter_local_notifications
依赖:
dependencies:
flutter:
sdk: flutter
flutter_local_notifications: ^9.0.0
然后,运行flutter pub get
来安装依赖。
接下来,你可以使用以下代码来设置并展示一个本地通知:
import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
@override
void initState() {
super.initState();
initialiseNotifications();
}
// 初始化通知设置
initialiseNotifications() {
var initializationSettingsAndroid =
AndroidInitializationSettings('app_icon');
var initializationSettingsIOS = IOSInitializationSettings();
var initializationSettings = InitializationSettings(
android: initializationSettingsAndroid, iOS: initializationSettingsIOS);
flutterLocalNotificationsPlugin.initialize(initializationSettings,
onSelectNotification: onSelectNotification);
}
// 当用户点击通知时调用的回调
onSelectNotification(String payload) {
if (payload != null) {
debugPrint('Notification payload: ' + payload);
}
}
// 展示通知
showNotification() async {
var androidPlatformChannelSpecifics = AndroidNotificationDetails(
'channel_id', 'channel_name', 'channel_description',
importance: Importance.max, priority: Priority.high);
var iOSPlatformChannelSpecifics = IOSNotificationDetails();
var platformChannelSpecifics = NotificationDetails(
android: androidPlatformChannelSpecifics,
iOS: iOSPlatformChannelSpecifics);
await flutterLocalNotificationsPlugin.show(
0, 'New Notification', 'This is a test notification', platformChannelSpecifics,
payload: 'Test payload');
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
评论已关闭