微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

为什么 0 待处理通知

如何解决为什么 0 待处理通知

我正在使用 flutter_local_notification V 5.00+3调用 FlutterlocalnotificationsPlugin.pendingNotificationRequests()

总是返回 0(零),即使我执行

FlutterlocalnotificationsPlugin().show

两次不点击通知,留下通知代码如下所示,取自示例,简单修改消息的id

import 'dart:async';
import 'dart:io';
import 'dart:typed_data';
import 'dart:ui';

import 'package:device_info/device_info.dart';
import 'package:Flutter/cupertino.dart';
import 'package:Flutter/material.dart';
import 'package:Flutter/services.dart';
import 'package:Flutter_local_notifications/Flutter_local_notifications.dart';
import 'package:Flutter_native_timezone/Flutter_native_timezone.dart';
import 'package:http/http.dart' as http;
import 'package:path_provider/path_provider.dart';
import 'package:rxdart/subjects.dart';

final FlutterlocalnotificationsPlugin FlutterlocalnotificationsPlugin =
    FlutterlocalnotificationsPlugin();

/// Streams are created so that app can respond to notification-related events
/// since the plugin is initialised in the `main` function
final BehaviorSubject<Receivednotification> didReceivelocalnotificationSubject =
    BehaviorSubject<Receivednotification>();

final BehaviorSubject<String?> selectNotificationSubject =
    BehaviorSubject<String?>();

const MethodChannel platform =
    MethodChannel('dexterx.dev/Flutter_local_notifications_example');

class Receivednotification {
  Receivednotification({
    required this.id,required this.title,required this.body,required this.payload,});

  final int id;
  final String? title;
  final String? body;
  final String? payload;
}

String? selectednotificationPayload;

/// IMPORTANT: running the following code on its own won't work as there is
/// setup required for each platform head project.
///
/// Please download the complete example app from the GitHub repository where
/// all the setup has been done
Future<void> main() async {
  // needed if you intend to initialize in the `main` function
  WidgetsFlutterBinding.ensureInitialized();

  final NotificationApplaunchdetails? notificationApplaunchdetails =
      await FlutterlocalnotificationsPlugin.getNotificationApplaunchdetails();
  String initialRoute = HomePage.routeName;
  if (notificationApplaunchdetails?.didNotificationLaunchApp ?? false) {
    selectednotificationPayload = notificationApplaunchdetails!.payload;
    initialRoute = SecondPage.routeName;
  }

  const AndroidInitializationSettings initializationSettingsAndroid =
      AndroidInitializationSettings('@mipmap/ic_launcher');

  /// Note: permissions aren't requested here just to demonstrate that can be
  /// done later
  final IOSInitializationSettings initializationSettingsIOS =
      IOSInitializationSettings(
          requestAlertPermission: false,requestBadgePermission: false,requestSoundPermission: false,onDidReceivelocalnotification:
              (int id,String? title,String? body,String? payload) async {
            didReceivelocalnotificationSubject.add(Receivednotification(
                id: id,title: title,body: body,payload: payload));
          });
  const MacOSInitializationSettings initializationSettingsMacOS =
      MacOSInitializationSettings(
          requestAlertPermission: false,requestSoundPermission: false);
  final InitializationSettings initializationSettings = InitializationSettings(
      android: initializationSettingsAndroid,iOS: initializationSettingsIOS,macOS: initializationSettingsMacOS);
  await FlutterlocalnotificationsPlugin.initialize(initializationSettings,onSelectNotification: (String? payload) async {
    if (payload != null) {
      debugPrint('notification payload: $payload');
    }
    selectednotificationPayload = payload;
    selectNotificationSubject.add(payload);
  });
  runApp(
    MaterialApp(
      initialRoute: initialRoute,routes: <String,WidgetBuilder>{
        HomePage.routeName: (_) => HomePage(notificationApplaunchdetails),SecondPage.routeName: (_) => SecondPage(selectednotificationPayload)
      },),);
}

class PaddedElevatedButton extends StatelessWidget {
  const PaddedElevatedButton({
    required this.buttonText,required this.onpressed,Key? key,}) : super(key: key);

  final String buttonText;
  final VoidCallback onpressed;

  @override
  Widget build(BuildContext context) => Padding(
        padding: const EdgeInsets.fromLTRB(0,8),child: ElevatedButton(
          onpressed: onpressed,child: Text(buttonText),);
}

class HomePage extends StatefulWidget {
  const HomePage(
    this.notificationApplaunchdetails,{
    Key? key,}) : super(key: key);

  static const String routeName = '/';

  final NotificationApplaunchdetails? notificationApplaunchdetails;

  bool get didNotificationLaunchApp =>
      notificationApplaunchdetails?.didNotificationLaunchApp ?? false;

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  @override
  void initState() {
    super.initState();
    _requestPermissions();
    _configureDidReceivelocalnotificationSubject();
    _configureSelectNotificationSubject();
  }

  void _configureSelectNotificationSubject() {
    selectNotificationSubject.stream.listen((String? payload) async {
      await Navigator.pushNamed(context,'/secondPage');
    });
  }

  void _requestPermissions() {
    FlutterlocalnotificationsPlugin
        .resolvePlatformSpecificImplementation<
            IOSFlutterlocalnotificationsPlugin>()
        ?.requestPermissions(
          alert: true,badge: true,sound: true,);
    FlutterlocalnotificationsPlugin
        .resolvePlatformSpecificImplementation<
            MacOSFlutterlocalnotificationsPlugin>()
        ?.requestPermissions(
          alert: true,);
  }

  void _configureDidReceivelocalnotificationSubject() {
    didReceivelocalnotificationSubject.stream
        .listen((Receivednotification receivednotification) async {
      await showDialog(
        context: context,builder: (BuildContext context) => CupertinoAlertDialog(
          title: receivednotification.title != null
              ? Text(receivednotification.title!)
              : null,content: receivednotification.body != null
              ? Text(receivednotification.body!)
              : null,actions: <Widget>[
            CupertinoDialogAction(
              isDefaultAction: true,onpressed: () async {
                Navigator.of(context,rootNavigator: true).pop();
                await Navigator.push(
                  context,MaterialPageRoute<void>(
                    builder: (BuildContext context) =>
                        SecondPage(receivednotification.payload),);
              },child: const Text('Ok'),)
          ],);
    });
  }

  @override
  void dispose() {
    didReceivelocalnotificationSubject.close();
    selectNotificationSubject.close();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) => MaterialApp(
        home: Scaffold(
          appBar: AppBar(
            title: const Text('Plugin example app'),body: SingleChildScrollView(
            child: Padding(
              padding: const EdgeInsets.all(8),child: Center(
                child: Column(
                  children: <Widget>[
                    const Padding(
                      padding: EdgeInsets.fromLTRB(0,child: Text(
                          'Tap on a notification when it appears to trigger'
                          ' navigation'),Padding(
                      padding: const EdgeInsets.fromLTRB(0,child: Text.rich(
                        TextSpan(
                          children: <Inlinespan>[
                            const TextSpan(
                              text: 'Did notification launch app? ',style: TextStyle(fontWeight: FontWeight.bold),TextSpan(
                              text: '${widget.didNotificationLaunchApp}',)
                          ],if (widget.didNotificationLaunchApp)
                      Padding(
                        padding: const EdgeInsets.fromLTRB(0,child: Text.rich(
                          TextSpan(
                            children: <Inlinespan>[
                              const TextSpan(
                                text: 'Launch notification payload: ',TextSpan(
                                text: widget
                                    .notificationApplaunchdetails!.payload,)
                            ],PaddedElevatedButton(
                      buttonText: 'Show 1 plain notification with payload',onpressed: () async {
                        await _showNotification(1);
                      },PaddedElevatedButton(
                      buttonText: 'Show 2 plain notification with payload',onpressed: () async {
                        await _showNotification(2);
                      },PaddedElevatedButton(
                      buttonText: 'Check pending notifications',onpressed: () async {
                        await _checkPendingNotificationRequests();
                      },],);

  Future<void> _showNotification(int idOfMsg) async {
    const AndroidNotificationDetails androidplatformChannelSpecifics =
        AndroidNotificationDetails(
            'your channel id','your channel name','your channel description',importance: Importance.max,priority: Priority.high,ticker: 'ticker');
    const NotificationDetails platformChannelSpecifics =
        NotificationDetails(android: androidplatformChannelSpecifics);
    await FlutterlocalnotificationsPlugin.show(
        idOfMsg,'plain title'+ idOfMsg.toString(),'plain body',platformChannelSpecifics,payload: 'item x' + idOfMsg.toString());
  }

  Future<void> _cancelNotification() async {
    await FlutterlocalnotificationsPlugin.cancel(0);
  }

  Future<void> _checkPendingNotificationRequests() async {
    final List<PendingNotificationRequest> pendingNotificationRequests =
        await FlutterlocalnotificationsPlugin.pendingNotificationRequests();
    return showDialog<void>(
      context: context,builder: (BuildContext context) => AlertDialog(
        content:
            Text('${pendingNotificationRequests.length} pending notification '
                'requests'),actions: <Widget>[
          TextButton(
            onpressed: () {
              Navigator.of(context).pop();
            },child: const Text('OK'),);
  }

  Future<void> _cancelAllNotifications() async {
    await FlutterlocalnotificationsPlugin.cancelAll();
  }
}

class SecondPage extends StatefulWidget {
  const SecondPage(
    this.payload,}) : super(key: key);

  static const String routeName = '/secondPage';

  final String? payload;

  @override
  State<StatefulWidget> createState() => SecondPageState();
}

class SecondPageState extends State<SecondPage> {
  String? _payload;
  @override
  void initState() {
    super.initState();
    _payload = widget.payload;
  }

  @override
  Widget build(BuildContext context) => Scaffold(
        appBar: AppBar(
          title: Text('Second Screen ${_payload ?? ''}  with payload: '),body: Center(
          child: ElevatedButton(
            onpressed: () {
              Navigator.pop(context);
            },child: const Text('Go back!'),);
}

请帮助我获取仍未被用户点击或取消的通知列表。

解决方法

pendingNotificationRequests 用于尚未出现在通知面板中的预定通知。

getActiveNotifications 用于通知面板中可用的通知。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。