# Flutter 好用package - awesome_notifications 介紹 ## awesome_notifications 可客製化手機通知,目前只支援安卓及IOS,官網上範例清楚可直接看但github上有多個issue未解須隨時關注。 ``` flutter pub add awesome_notifications ``` [官網](https://pub.dev/packages/awesome_notifications) ### 程式範例 #### 初始化 `AwesomeNotifications().initialize`需在runApp前進行初始化: main.dart ```dart //由於通知初始化時間較久固已非同步進行處理 void main() async { WidgetsFlutterBinding.ensureInitialized(); //通知初始化 NotificationUtils.initNotification(); runApp(const MyApp()); } ``` notifications.dart ```dart static Future<void> initNotification() async { await AwesomeNotifications().initialize( //通知圖示 'resource://drawable/res_timer_icon', //頻道 [ NotificationChannel( channelKey: 'alarm_channel', //此頻道的key須為獨一無二 channelName: '倒數計時器', defaultColor: Colors.blue, importance: NotificationImportance.High, playSound: true, channelShowBadge: false, channelDescription: '倒數計時器提醒通知', ), ], ); } ``` 初始化時須包含: 1. 通知圖示([自製簡單icon](https://romannurik.github.io/AndroidAssetStudio/icons-launcher.html#foreground.type=clipart&foreground.clipart=access_alarm&foreground.space.trim=0&foreground.space.pad=0.05&foreColor=rgb(255%2C%20255%2C%20255)&backColor=rgb(0%2C%200%2C%200)&crop=0&backgroundShape=circle&effects=none&name=res_timer_icon)),並將圖示放入資料夾(`\android\app\src\main\res`)內,若為null則預設APP圖示 2. 頻道`NotificationChannel` ### 檢查是否允許顯示通知 `AwesomeNotifications().isNotificationAllowed()`,需在各頁面init時詢問: home_page.dart ```dart @override void initState() { super.initState(); //檢查是否允許顯示通知 NotificationUtils.allowedNotification(context); } ``` notifications.dart,跳出提示框進行詢問 ```dart static void allowedNotification(context) { AwesomeNotifications().isNotificationAllowed().then( (isAllowed) { if (!isAllowed) { showDialog( context: context, builder: (context) => AlertDialog( title: Text('Allow Notifications'), content: Text('Our app would like to send you notifications'), actions: [ TextButton( onPressed: () { Navigator.pop(context); }, child: Text( 'Don\'t Allow', style: TextStyle(color: Colors.grey, fontSize: 18), ), ), TextButton( onPressed: () => AwesomeNotifications() .requestPermissionToSendNotifications() .then((_) => Navigator.pop(context)), child: Text( 'Allow', style: TextStyle( color: Colors.teal, fontSize: 18, fontWeight: FontWeight.bold, ), ), ), ], ), ); } }, ); } ``` ### 建立通知模板 `AwesomeNotifications().createNotification`,此處示範點擊按鈕後發送通知: notifications.dart ```dart static Future<void> scheduleNotificationWithWakeUp(int sec) async { await AwesomeNotifications().createNotification( content: NotificationContent( id: 3, //若希望每則通知不覆蓋id需不重複 channelKey: 'alarm_channel', //哪一個頻道 title: 'Hey! Wake up!!', body: 'Its time to wake up!', color: Colors.blueGrey, category: NotificationCategory.Alarm, autoDismissible: true, ), //點擊後5秒鐘就會顯示通知 schedule: NotificationInterval(interval: sec, preciseAlarm: true), //通知的按鈕,除按鈕外依據buttonType也可以是其他樣式 actionButtons: [ NotificationActionButton( key: 'SLEEP_1', label: '再睡一下', showInCompactView: false, enabled: true, buttonType: ActionButtonType.KeepOnTop), NotificationActionButton( key: 'OK', label: '已起床', showInCompactView: false, enabled: true, buttonType: ActionButtonType.KeepOnTop), ]); } ``` ### 監聽通知事件 `AwesomeNotifications().actionStream.listen`,監聽點擊通知上的按鈕收到的事件,需在各頁面init時詢問: home_page.dart ```dart @override void initState() { super.initState(); //檢查是否允許顯示通知 NotificationUtils.allowedNotification(context); //監聽通知事件 NotificationUtils.listenNotification(); } ``` notifications.dart ```dart static void listenNotification() { AwesomeNotifications().actionStream.listen((receivedAction) { switch (receivedAction.channelKey) { case 'alarm_channel': switch (receivedAction.buttonKeyPressed) { case 'SLEEP_1': NotificationUtils.timerNotification(60); break; case 'OK': AndroidForegroundService.stopForeground(); break; } break; } }); } ``` ### 注意事項 * minSdkVersion有最低限制記的要調整`build.gradle` ![](https://i.imgur.com/LTewWuL.png) * 依據不同功能的通知也需要加上不同的permission ``` <uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM"/> ``` ![](https://i.imgur.com/5ak9qmh.png) 要不然會報錯 ![](https://i.imgur.com/A7mnDce.png) ###### tags: `flutter` `firebase`