在 Android 中使用 Notification 是比较简单的,这里不多做赘述,但若在 flutter 中要使用Notification 我们可以通过 Flutter Local Notifications Plugin 这个插件来实现。
dependencies:
flutter_local_notifications: ^0.4.4+2
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
var flutterLocalNotificationsPlugin = new FlutterLocalNotificationsPlugin();
@override
initState() {
super.initState();
var initializationSettingsAndroid =
new AndroidInitializationSettings('app_icon');
var initializationSettingsIOS = new IOSInitializationSettings(
onDidReceiveLocalNotification: onDidRecieveLocalNotification);
var initializationSettings = new InitializationSettings(
initializationSettingsAndroid, initializationSettingsIOS);
flutterLocalNotificationsPlugin.initialize(initializationSettings,
onSelectNotification: onSelectNotification);
}
其中 ‘app_icon’ 是指通知上的图标,将该图标放至 drawable 目录下即可。
onDidRecieveLocalNotification 这个是IOS端接收到通知所作的处理的方法。
Future onDidRecieveLocalNotification(
int id, String title, String body, String payload) async {
// 展示通知内容的 dialog.
showDialog(
context: context,
builder: (BuildContext context) => new CupertinoAlertDialog(
title: new Text(title),
content: new Text(body),
actions: [
CupertinoDialogAction(
isDefaultAction: true,
child: new Text('Ok'),
onPressed: () async {
Navigator.of(context, rootNavigator: true).pop();
await Navigator.push(
context,
new MaterialPageRoute(
builder: (context) => new SecondScreen(payload),
),
);
},
)
],
),
);
}
onSelectNotification 是对通知被点击的监听方法,这个参数是可选的。
Future onSelectNotification(String payload) async {
if (payload != null) {
debugPrint('notification payload: ' + payload);
}
//payload 可作为通知的一个标记,区分点击的通知。
if(payload != null && payload == "complete") {
await Navigator.push(
context,
new MaterialPageRoute(builder: (context) => new SecondScreen(payload)),
);
}
}
至此,初始化全部完成了,至于如何显示通知,这里只介绍普通的通知的用法。
Future _showNotification() async {
//安卓的通知配置,必填参数是渠道id, 名称, 和描述, 可选填通知的图标,重要度等等。
var androidPlatformChannelSpecifics = new AndroidNotificationDetails(
'your channel id', 'your channel name', 'your channel description',
importance: Importance.Max, priority: Priority.High);
//IOS的通知配置
var iOSPlatformChannelSpecifics = new IOSNotificationDetails();
var platformChannelSpecifics = new NotificationDetails(
androidPlatformChannelSpecifics, iOSPlatformChannelSpecifics);
//显示通知,其中 0 代表通知的 id,用于区分通知。
await flutterLocalNotificationsPlugin.show(
0, 'title', 'content', platformChannelSpecifics,
payload: 'complete');
}
移除通知可以使用 cancel 方法。
//删除单个通知
Future _cancelNotification() async {
//参数 0 为需要删除的通知的id
await flutterLocalNotificationsPlugin.cancel(0);
}
//删除所有通知
Future _cancelAllNotifications() async {
await flutterLocalNotificationsPlugin.cancelAll();
}