在 Android 中使用 Notification 是比較簡單的,這裏不多做贅述,但若在 flutter 中要使用Notification 我們可以通過 Flutter Local Notifications Plugin 這個插件來實現。
- 在 pubspec.yaml 裏面添加依賴。
dependencies:
flutter_local_notifications: ^0.4.4+2
- 在 dart 文件中導入包。
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
- 在 initState 裏面初始化。
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();
}
運行效果
更多詳情請移步至Flutter Local Notifications Plugin 官網