Flutter: flutter_local_notifications - learning of message push

foreword

Note: Just started learning, if you encounter problems when using some cases, you can Baidu, view official cases, and official github by yourself.

Introduction
Flutter Local Notifications is a plugin for displaying local notifications in Flutter applications. It provides a simple and powerful way to send notifications on the device so that the user can receive them while the app is in the background or the device is locked.

Using the Flutter Local Notifications plugin, various types of notifications can be created and scheduled, including:

  1. Instant notifications: Notifications that appear immediately to convey important news or reminders to the user.
  2. Recurring notifications: Notifications that can be displayed repeatedly at specified intervals, such as daily or weekly reminders.
  3. Timed Notifications: Notifications triggered at specific dates and times to schedule future events or reminders.

By using Flutter Local Notifications, you can customize the appearance and behavior of notifications, including titles, content, icons, sounds, vibration patterns, and tap actions. Additionally, user interaction with notifications can be handled, such as performing a specific action when the user clicks on the notification.

The Flutter Local Notifications plugin is simple to use and easy to integrate into Flutter projects. It provides a set of easy-to-use APIs to easily create and manage notifications. Additionally, it is compatible with both Android and iOS platforms and can operate with the same code base on both platforms.

Official address
https://pub-web.flutter-io.cn/packages/flutter_local_notifications

Remarks: Here only learn about the basic use of Android

study

Prepare

Install

flutter pub add flutter_local_notifications

instant notification

Notification helper class
NotificationHelper

// 导入包
import 'package:flutter_local_notifications/flutter_local_notifications.dart';

class NotificationHelper {
    
    
  // 使用单例模式进行初始化
  static final NotificationHelper _instance = NotificationHelper._internal();
  factory NotificationHelper() => _instance;
  NotificationHelper._internal();

  // FlutterLocalNotificationsPlugin是一个用于处理本地通知的插件,它提供了在Flutter应用程序中发送和接收本地通知的功能。
  final FlutterLocalNotificationsPlugin _notificationsPlugin =
      FlutterLocalNotificationsPlugin();

  // 初始化函数
  Future<void> initialize() async {
    
    
    // AndroidInitializationSettings是一个用于设置Android上的本地通知初始化的类
    // 使用了app_icon作为参数,这意味着在Android上,应用程序的图标将被用作本地通知的图标。
    const AndroidInitializationSettings initializationSettingsAndroid =
    AndroidInitializationSettings('@mipmap/ic_launcher');
    // 15.1是DarwinInitializationSettings,旧版本好像是IOSInitializationSettings(有些例子中就是这个)
    const DarwinInitializationSettings initializationSettingsIOS =
        DarwinInitializationSettings();
    // 初始化
    const InitializationSettings initializationSettings =
        InitializationSettings(
            android: initializationSettingsAndroid,
            iOS: initializationSettingsIOS);
    await _notificationsPlugin.initialize(initializationSettings);
  }

//  显示通知
  Future<void> showNotification(
      {
    
    required String title, required String body}) async {
    
    
    // 安卓的通知
    // 'your channel id':用于指定通知通道的ID。
    // 'your channel name':用于指定通知通道的名称。
    // 'your channel description':用于指定通知通道的描述。
    // Importance.max:用于指定通知的重要性,设置为最高级别。
    // Priority.high:用于指定通知的优先级,设置为高优先级。
    // 'ticker':用于指定通知的提示文本,即通知出现在通知中心的文本内容。
    const AndroidNotificationDetails androidNotificationDetails =
        AndroidNotificationDetails('your.channel.id', 'your channel name',
            channelDescription: 'your channel description',
            importance: Importance.max,
            priority: Priority.high,
            ticker: 'ticker');

    // ios的通知
    const String darwinNotificationCategoryPlain = 'plainCategory';
    const DarwinNotificationDetails iosNotificationDetails =
        DarwinNotificationDetails(
      categoryIdentifier: darwinNotificationCategoryPlain, // 通知分类
    );
    // 创建跨平台通知
    const NotificationDetails platformChannelSpecifics =
        NotificationDetails(android: androidNotificationDetails,iOS: iosNotificationDetails);

    // 发起一个通知
    await _notificationsPlugin.show(
      1,
      title,
      body,
      platformChannelSpecifics,
    );
  }
}

use

main() async {
    
    
  //用于确保Flutter的Widgets绑定已经初始化。
  WidgetsFlutterBinding.ensureInitialized();

  // 初始化通知帮助类
  NotificationHelper notificationHelper = NotificationHelper();
  await notificationHelper.initialize();
  runApp(const MyApp());
}
class SwitcherContainerState extends State<SwitcherContainer> {
    
    
  final NotificationHelper _notificationHelper = NotificationHelper();
  
  Widget build(BuildContext context) {
    
    
    return Center(
        child: ElevatedButton(
            onPressed: () {
    
    
              _notificationHelper.showNotification(
                title: 'Hello',
                body: 'This is a notification!',
              );
            },
            child: const Text("发起通知")));
  }
}

Notice:

  • Be sure to initialize in the main function, otherwise the following error will be reported (Baidu spent a long time, and finally found that I forgot to initialize)
    insert image description here
  • You need to enable the notification permission of the application, otherwise you may not be able to notify

insert image description here

periodic notification

 // 周期性通知
  Future<void> scheduleNotification({
    
    
    required int id,
    required String title,
    required String body,
  }) async {
    
    
    const AndroidNotificationDetails androidNotificationDetails =
        AndroidNotificationDetails('your.channel.id', 'your channel name',
            channelDescription: 'your channel description',
            importance: Importance.max,
            priority: Priority.high,
            ticker: 'ticker');

    // ios的通知
    const String darwinNotificationCategoryPlain = 'plainCategory';
    const DarwinNotificationDetails iosNotificationDetails =
        DarwinNotificationDetails(
      categoryIdentifier: darwinNotificationCategoryPlain, // 通知分类
    );
    // 创建跨平台通知
    const NotificationDetails platformChannelSpecifics = NotificationDetails(
        android: androidNotificationDetails, iOS: iosNotificationDetails);
// 发起通知
    await _notificationsPlugin.periodicallyShow(
        id, title, body, RepeatInterval.everyMinute, platformChannelSpecifics);
  }
}

Here I set a notification every minute. Note: If you initiate a notification at 10:01, there will be no notification message at 10:01, but a notification will be initiated every minute from 10:02.

Regular notification

// 定时通知
Future<void> zonedScheduleNotification(
    {
    
    required int id,
    required String title,
    required String body,
    required DateTime scheduledDateTime}) async {
    
    
  const AndroidNotificationDetails androidNotificationDetails =
      AndroidNotificationDetails('your.channel.id', 'your channel name',
          channelDescription: 'your channel description',
          importance: Importance.max,
          priority: Priority.high,
          ticker: 'ticker');

  // ios的通知
  const String darwinNotificationCategoryPlain = 'plainCategory';
  const DarwinNotificationDetails iosNotificationDetails =
      DarwinNotificationDetails(
    categoryIdentifier: darwinNotificationCategoryPlain, // 通知分类
  );
  // 创建跨平台通知
  const NotificationDetails platformChannelSpecifics = NotificationDetails(
      android: androidNotificationDetails, iOS: iosNotificationDetails);
  // 发起通知
  await _notificationsPlugin.zonedSchedule(
    id, title, body,
    tz.TZDateTime.from(scheduledDateTime, tz.local), // 使用本地时区的时间
    platformChannelSpecifics,
    uiLocalNotificationDateInterpretation:
        UILocalNotificationDateInterpretation.absoluteTime, // 设置通知的触发时间是觉得时间
  );
}

Note: The parameters in the figure below scheduledDateare TZDateTimetypes. After looking at the official example, you need to download timezone the library.
timezoneIt is used to process time zone information, which can make it more convenient and accurate to create and process date time objects on different platforms.

Official address
https://pub-web.flutter-io.cn/packages/timezone

Install

flutter pub add timezone

Initialization Just initialize it in the function of
the notification auxiliary classNotificationHelperinitialize

import 'package:timezone/timezone.dart' as tz;
import 'package:timezone/data/latest.dart' as tz;

//  初始化tz
tz.initializeTimeZones();

insert image description here
insert image description here

other

In addition to the above three, there are other forms of notification, such as (the following content has not been tested)

long text

final androidPlatformChannelSpecifics = AndroidNotificationDetails(
  'channel_id',
  'channel_name',
  'channel_description',
  styleInformation: BigTextStyleInformation('大文本内容'),
);

big picture

final androidPlatformChannelSpecifics = AndroidNotificationDetails(
  'channel_id',
  'channel_name',
  'channel_description',
  styleInformation: BigPictureStyleInformation(
    FilePathAndroidBitmap('图片路径'),
    largeIcon: FilePathAndroidBitmap('大图标路径'),
  ),
);

There are also some parameters such as media style, with progress bar, etc. You can AndroidNotificationDetailsfind the corresponding parameters.
For IOS, the notification style is restricted by Apple, and some simple operations can be realized through DarwinNotificationDetailsthe attachmentsparameters.

Guess you like

Origin blog.csdn.net/weixin_41897680/article/details/131947231