Flutter通知插件FlutterLocalNotificationsPlugin

FlutterLocalNotificationsPlugin 是一个插件,它不会自动启动。如果您的应用在启动时无需立即显示通知,则可以延迟初始化插件,直到需要显示通知时,可以使用如下方法来实现:

1. 在应用程序的主屏幕或页面中,在需要显示通知的地方调用 FlutterLocalNotificationsPlugin 的初始化方法。

2. 当需要发送通知时,请检查 FlutterLocalNotificationsPlugin 是否已被初始化。如果没有,请先调用初始化方法。

3. 发送通知并关闭 FlutterLocalNotificationsPlugin。 以下是示例代码:

import 'package:flutter/foundation.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';

class GlobalNotifyPlugin {
// 延迟初始化 FlutterLocalNotificationsPlugin
  static FlutterLocalNotificationsPlugin _notifyPlugin;

  static Future initNotifications() async {
    if (_notifyPlugin == null) {
      _notifyPlugin = FlutterLocalNotificationsPlugin();
      _notifyPlugin.initialize(
          InitializationSettings(
              android: AndroidInitializationSettings("@mipmap/ic_launcher"),
              iOS: IOSInitializationSettings()),
          onSelectNotification: onSelectNotification);
    }
  }

  //展示通知
  static Future showNotification({String title, String body}) async {
    await initNotifications();

    AndroidNotificationDetails androidNotificationDetails =
        AndroidNotificationDetails('your channel id', 'your channel name',
            channelDescription: 'your channel description',
            importance: Importance.max,
            priority: Priority.high,
            ticker: 'ticker');

    IOSNotificationDetails iosNotificationDetails = IOSNotificationDetails();

    _notifyPlugin.show(
        DateTime.now().millisecondsSinceEpoch >> 10, //时间戳,唯一标识
        title,
        body,
        NotificationDetails(
            android: androidNotificationDetails, iOS: iosNotificationDetails),
        payload: 'item x');
  }

  static Future onSelectNotification(String payload) async {
    if (payload != null) {
      debugPrint('notification payload: $payload');
    }
// TODO: Handle notification tap
  }
}

在上面的代码中,我们首先定义了一个 FlutterLocalNotificationsPlugin 的全局变量 _notifyPlugin,并在 initNotifications() 方法中对其进行初始化。在 showNotification() 方法中,我们检查 FlutterLocalNotificationsPlugin 是否已被初始化,如果没有,则调用 initNotifications() 方法。最后,我们使用 flutterLocalNotificationsPlugin.show() 方法显示通知。

猜你喜欢

转载自blog.csdn.net/lqw200931116/article/details/130879439