想定読者
Flutterで標準アプリの設定の通知を許可の状態を取得したい
どこの画面のこと?
パッケージ追加
flutter pub add flutter_local_notifications
dependencies:
flutter_local_notifications: ^20.0.0
実装
とりあえずサービスクラスにしましたが、クラス内の処理を同じように書けば取得できます。
import 'dart:io';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
/// 通知状態の取得を担うサービスクラス
///
/// - Android: AndroidFlutterLocalNotificationsPlugin.areNotificationsEnabled()
/// - iOS: IOSFlutterLocalNotificationsPlugin.checkPermissions() の
/// isEnabled または isProvisionalEnabled が true の場合に true
class NotificationService {
/// constructor
NotificationService() : _plugin = FlutterLocalNotificationsPlugin();
final FlutterLocalNotificationsPlugin _plugin;
/// 通知設定がオンかどうかを取得する
Future<bool> areNotificationsEnabled() async {
if (Platform.isAndroid) {
final androidImplementation = _plugin
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin
>();
return await androidImplementation?.areNotificationsEnabled() ?? false;
} else if (Platform.isIOS) {
final iosImplementation = _plugin
.resolvePlatformSpecificImplementation<
IOSFlutterLocalNotificationsPlugin
>();
final notificationsEnabledOptions = await iosImplementation
?.checkPermissions();
return (notificationsEnabledOptions?.isEnabled ?? false) ||
(notificationsEnabledOptions?.isProvisionalEnabled ?? false);
}
return false;
}
}
感想
permission_handlerパッケージの方かと思ってひたすら試していましたが、flutter_local_notificationsを使う形でした。
内部でメソッドチャネルであれこれ呼んでいるようです
