Flutter本地通知插件flutter_local_notifications_support的使用

Flutter本地通知插件flutter_local_notifications_support的使用

简介

flutter_local_notifications 是一个跨平台插件,用于在应用程序中显示本地通知。它支持 Android 和 iOS 平台,并提供了丰富的功能来满足各种通知需求。

特点包括:

  • 显示基本通知。
  • 定时显示通知。
  • 每隔指定时间重复显示通知。
  • 自定义通知图标和声音。
  • 支持通知分组。
  • 支持 Android 的全屏意图通知。

支持的平台

  • Android 4.1+ 使用 NotificationCompat APIs,支持旧版本设备。
  • iOS 8.0+ 在 iOS 10 或更高版本中使用 UserNotifications 框架,在较旧版本中使用 UILocalNotification APIs。
  • macOS 10.11+ 在 macOS 10.14 或更高版本中使用 UserNotifications 框架,在较旧版本中使用 NSUserNotification APIs。

功能截图

平台 截图
Android
iOS
macOS

初始化

首先,创建并初始化插件实例:

import 'package:flutter_local_notifications/flutter_local_notifications.dart';

final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
    FlutterLocalNotificationsPlugin();

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  const AndroidInitializationSettings initializationSettingsAndroid =
      AndroidInitializationSettings('app_icon');

  final IOSInitializationSettings initializationSettingsIOS =
      IOSInitializationSettings(onDidReceiveLocalNotification: onDidReceiveLocalNotification);

  final InitializationSettings initializationSettings = InitializationSettings(
    android: initializationSettingsAndroid,
    iOS: initializationSettingsIOS,
  );

  await flutterLocalNotificationsPlugin.initialize(initializationSettings,
      onSelectNotification: selectNotification);
}

Future<void> selectNotification(String payload) async {
  if (payload != null) {
    debugPrint('notification payload: $payload');
  }
  await Navigator.push(
    context,
    MaterialPageRoute(builder: (context) => SecondScreen(payload)),
  );
}

显示通知

const AndroidNotificationDetails androidPlatformChannelSpecifics =
    AndroidNotificationDetails(
        'your channel id', 'your channel name', 'your channel description',
        importance: Importance.max,
        priority: Priority.high,
        showWhen: false);
const NotificationDetails platformChannelSpecifics =
    NotificationDetails(android: androidPlatformChannelSpecifics);
await flutterLocalNotificationsPlugin.show(
    0, 'plain title', 'plain body', platformChannelSpecifics,
    payload: 'item x');

定时通知

await flutterLocalNotificationsPlugin.zonedSchedule(
    0,
    'scheduled title',
    'scheduled body',
    tz.TZDateTime.now(tz.local).add(const Duration(seconds: 5)),
    const NotificationDetails(
        android: AndroidNotificationDetails('your channel id',
            'your channel name', 'your channel description')),
    androidAllowWhileIdle: true,
    uiLocalNotificationDateInterpretation:
        UILocalNotificationDateInterpretation.absoluteTime);

周期性通知

const AndroidNotificationDetails androidPlatformChannelSpecifics =
    AndroidNotificationDetails('repeating channel id',
        'repeating channel name', 'repeating description');
const NotificationDetails platformChannelSpecifics =
    NotificationDetails(android: androidPlatformChannelSpecifics);
await flutterLocalNotificationsPlugin.periodicallyShow(0, 'repeating title',
    'repeating body', RepeatInterval.everyMinute, platformChannelSpecifics,
    androidAllowWhileIdle: true);

获取待处理的通知请求

final List<PendingNotificationRequest> pendingNotificationRequests =
    await flutterLocalNotificationsPlugin.pendingNotificationRequests();

取消通知

await flutterLocalNotificationsPlugin.cancel(0);

取消所有通知

await flutterLocalNotificationsPlugin.cancelAll();

更多关于Flutter本地通知插件flutter_local_notifications_support的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter本地通知插件flutter_local_notifications_support的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


flutter_local_notifications 是一个用于在 Flutter 应用中显示本地通知的插件。它支持 Android 和 iOS 平台,并且可以用于在应用的前台或后台显示通知。以下是如何使用 flutter_local_notifications 插件的基本步骤。

1. 添加依赖

首先,在 pubspec.yaml 文件中添加 flutter_local_notifications 依赖:

dependencies:
  flutter:
    sdk: flutter
  flutter_local_notifications: ^x.x.x  # 请使用最新版本

然后运行 flutter pub get 来安装依赖。

2. 初始化插件

在你的 Dart 文件中导入插件并初始化它。通常,你可以在 main.dart 文件中进行初始化。

import 'package:flutter_local_notifications/flutter_local_notifications.dart';

final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
    FlutterLocalNotificationsPlugin();

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  // 初始化通知插件
  const AndroidInitializationSettings initializationSettingsAndroid =
      AndroidInitializationSettings('@mipmap/ic_launcher');

  final InitializationSettings initializationSettings = InitializationSettings(
    android: initializationSettingsAndroid,
    // iOS 初始化设置(如果需要)
    iOS: IOSInitializationSettings(),
  );

  await flutterLocalNotificationsPlugin.initialize(initializationSettings);

  runApp(MyApp());
}

3. 配置通知渠道(仅 Android)

在 Android 8.0(API 级别 26)及以上版本中,通知必须通过通知渠道发送。你可以在初始化时配置通知渠道。

const AndroidNotificationChannel channel = AndroidNotificationChannel(
  'high_importance_channel', // id
  'High Importance Notifications', // title
  'This channel is used for important notifications.', // description
  importance: Importance.high,
);

await flutterLocalNotificationsPlugin
    .resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>()
    ?.createNotificationChannel(channel);

4. 显示通知

你可以使用 flutterLocalNotificationsPlugin.show 方法来显示通知。

void showNotification() async {
  const AndroidNotificationDetails androidPlatformChannelSpecifics =
      AndroidNotificationDetails(
    'high_importance_channel', // channelId
    'High Importance Notifications', // channelName
    'This channel is used for important notifications.', // channelDescription
    importance: Importance.high,
    priority: Priority.high,
    showWhen: false,
  );

  const NotificationDetails platformChannelSpecifics =
      NotificationDetails(android: androidPlatformChannelSpecifics);

  await flutterLocalNotificationsPlugin.show(
    0, // notification id
    'Notification Title', // title
    'This is the notification body', // body
    platformChannelSpecifics,
    payload: 'data', // optional payload
  );
}

5. 处理通知点击事件

你可以在初始化时设置一个回调函数来处理通知的点击事件。

await flutterLocalNotificationsPlugin.initialize(initializationSettings,
    onSelectNotification: (String? payload) async {
  if (payload != null) {
    debugPrint('notification payload: $payload');
  }
});

6. 调度通知

你还可以使用 flutterLocalNotificationsPlugin.zonedSchedule 方法来调度通知。

void scheduleNotification() async {
  const AndroidNotificationDetails androidPlatformChannelSpecifics =
      AndroidNotificationDetails(
    'high_importance_channel', // channelId
    'High Importance Notifications', // channelName
    'This channel is used for important notifications.', // channelDescription
    importance: Importance.high,
    priority: Priority.high,
    showWhen: false,
  );

  const NotificationDetails platformChannelSpecifics =
      NotificationDetails(android: androidPlatformChannelSpecifics);

  await flutterLocalNotificationsPlugin.zonedSchedule(
    0, // notification id
    'Scheduled Notification', // title
    'This is a scheduled notification', // body
    tz.TZDateTime.now(tz.local).add(const Duration(seconds: 5)), // schedule time
    platformChannelSpecifics,
    androidAllowWhileIdle: true, // Allow the notification to show even in Doze mode
    uiLocalNotificationDateInterpretation:
        UILocalNotificationDateInterpretation.absoluteTime,
  );
}

7. 取消通知

你可以使用 flutterLocalNotificationsPlugin.cancel 方法来取消通知。

void cancelNotification(int notificationId) async {
  await flutterLocalNotificationsPlugin.cancel(notificationId);
}

8. 取消所有通知

你可以使用 flutterLocalNotificationsPlugin.cancelAll 方法来取消所有通知。

void cancelAllNotifications() async {
  await flutterLocalNotificationsPlugin.cancelAll();
}

9. 处理权限(仅 iOS)

在 iOS 上,你需要请求通知权限。你可以在初始化时请求权限。

await flutterLocalNotificationsPlugin
    .resolvePlatformSpecificImplementation<IOSFlutterLocalNotificationsPlugin>()
    ?.requestPermissions(
  alert: true,
  badge: true,
  sound: true,
);

10. 处理后台通知

如果你需要在应用处于后台时处理通知,你可以使用 flutter_local_notifications 插件的 onDidReceiveNotificationResponse 回调。

await flutterLocalNotificationsPlugin.initialize(initializationSettings,
    onDidReceiveNotificationResponse: (NotificationResponse response) async {
  if (response.payload != null) {
    debugPrint('notification payload: ${response.payload}');
  }
});
回到顶部