Flutter本地通知插件simple_local_notifications的使用

Flutter本地通知插件simple_local_notifications的使用

simple_local_notifications 是一个简单的本地通知插件,允许设置标题、图标和内容。

开始使用

在使用 simple_local_notifications 插件之前,需要确保你的应用已获得必要的权限。对于 Android 版本大于 26 的设备,必须确保用户已经授予了通知权限(请查看示例项目了解一种检查方法)。

Android

如果使用的是 Android 版本 > 26,确保用户已经授予了通知权限。例如:

await Permission.notification.request();
iOS

目前尚未开发对 iOS 的支持。

macOS

目前尚未开发对 macOS 的支持。

Windows

目前尚未开发对 Windows 的支持。

Linux

目前尚未开发对 Linux 的支持。

示例代码

以下是一个完整的示例,展示了如何使用 simple_local_notifications 插件发送本地通知。

import 'package:flutter/material.dart';
import 'dart:async';

import 'package:permission_handler/permission_handler.dart';
import 'package:simple_local_notifications/models/notification.dart';
import 'package:simple_local_notifications/simple_local_notifications.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  [@override](/user/override)
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final _simpleLocalNotificationsPlugin = SimpleLocalNotifications();

  [@override](/user/override)
  void initState() {
    super.initState();
    initApplication();
  }

  // 初始化应用程序,创建通知渠道
  Future<void> initApplication() async {
    try {
      // 创建一个高优先级的通知渠道
      await _simpleLocalNotificationsPlugin.createNotificationChannel(
          channelId: "simple_local_notifications_channel_priority",
          channelName: "simple_local_notifications_priority",
          priority: SLNotificationPriority.high);
    } catch (e) {
      print(e.toString());
    }
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('插件示例应用'),
        ),
        body: Center(
          child: Column(
            children: [
              // 发送普通通知按钮
              TextButton(
                onPressed: () async {
                  // 请求通知权限
                  await Permission.notification.request();
                  // 发送通知
                  await _simpleLocalNotificationsPlugin.sendNotification(SLNotification(
                    title: "Hello world",
                    content: "来自 Flutter 插件的通知",
                    iconPath: "assets/icons/icon.png", // 图标路径
                  ));
                },
                child: const Text("发送通知"),
              ),
              // 发送高优先级通知按钮
              TextButton(
                onPressed: () async {
                  // 请求通知权限
                  await Permission.notification.request();
                  // 发送高优先级通知
                  await _simpleLocalNotificationsPlugin.sendNotification(SLNotification(
                    title: "Hello world",
                    content: "来自 Flutter 插件的通知",
                    iconPath: "assets/icons/icon.png", // 图标路径
                    channelId: "simple_local_notifications_channel_priority", // 通知渠道ID
                    channelName: "simple_local_notifications_priority", // 通知渠道名称
                    priority: SLNotificationPriority.high, // 优先级
                  ));
                },
                child: const Text("发送高优先级通知"),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

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

1 回复

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


当然,以下是如何在Flutter项目中使用simple_local_notifications插件来实现本地通知的一个详细示例。

1. 添加依赖

首先,你需要在pubspec.yaml文件中添加simple_local_notifications插件的依赖:

dependencies:
  flutter:
    sdk: flutter
  simple_local_notifications: ^x.y.z  # 请替换为最新版本号

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

2. 导入插件

在你的Dart文件中导入插件:

import 'package:simple_local_notifications/simple_local_notifications.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart' as flutterLocalNotifications;

3. 初始化插件

在你的main.dart或适当的初始化位置,配置并初始化插件:

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
  final SimpleLocalNotificationsPlugin simpleLocalNotificationsPlugin = SimpleLocalNotificationsPlugin();

  // 配置FlutterLocalNotificationsPlugin
  var initializationSettingsAndroid = new flutterLocalNotifications.AndroidInitializationSettings('@mipmap/ic_launcher');
  var initializationSettingsIOS = new flutterLocalNotifications.IOSInitializationSettings(requestAlertPermission: true, requestBadgePermission: true, requestSoundPermission: true);
  var initializationSettings = new flutterLocalNotifications.InitializationSettings(android: initializationSettingsAndroid, iOS: initializationSettingsIOS);
  flutterLocalNotificationsPlugin.initialize(initializationSettings, new flutterLocalNotifications.OnInitializationCompleteCallback {
    @override
    void onInitializationComplete(flutterLocalNotifications.InitializationStatus status) {
      if(!status.isEnabled) {
        print('Local notifications are not enabled on this device.');
        return;
      }
      print('Local notifications are enabled on this device.');

      // 配置SimpleLocalNotificationsPlugin
      simpleLocalNotificationsPlugin.initialize(flutterLocalNotificationsPlugin);
    }
  });

  runApp(MyApp());
}

4. 创建通知

在你的应用逻辑中创建和显示通知:

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Local Notifications Example'),
        ),
        body: Center(
          child: ElevatedButton(
            onPressed: () async {
              final SimpleLocalNotificationsPlugin simpleLocalNotificationsPlugin = SimpleLocalNotificationsPlugin();

              var androidPlatformChannelSpecifics = new flutterLocalNotifications.AndroidNotificationDetails(
                'your channel id',
                'Your Channel Name',
                'Your Channel Description',
                importance: flutterLocalNotifications.Importance.High,
                priority: flutterLocalNotifications.NotificationPriority.High
              );
              var iOSPlatformChannelSpecifics = new flutterLocalNotifications.IOSNotificationDetails();
              var platformChannelSpecifics = new flutterLocalNotifications.NotificationDetails(
                android: androidPlatformChannelSpecifics,
                iOS: iOSPlatformChannelSpecifics
              );

              await simpleLocalNotificationsPlugin.show(
                100, // id
                'Local Notification Title',
                'This is the body of the notification',
                platformChannelSpecifics
              );
            },
            child: Text('Show Notification'),
          ),
        ),
      ),
    );
  }
}

5. 处理通知点击事件

你可能还需要处理用户点击通知时的逻辑:

void configureSelectNotificationSubject(FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin) {
  flutterLocalNotificationsPlugin.onNotificationOpenedApp.listen((String payload) async {
    // 用户点击通知打开应用时的逻辑
    print('onNotificationOpenedApp: $payload');
  });

  flutterLocalNotificationsPlugin.onNotificationAction.listen((flutterLocalNotifications.NotificationAction action) async {
    // 用户点击通知中的按钮时的逻辑
    print('onNotificationAction: ${action.key}');
  });

  flutterLocalNotificationsPlugin.onSelectNotification.listen((String payload) async {
    // 用户点击通知(在通知栏中)时的逻辑,但不打开应用
    print('onSelectNotification: $payload');
  });
}

main函数中调用configureSelectNotificationSubject

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
  final SimpleLocalNotificationsPlugin simpleLocalNotificationsPlugin = SimpleLocalNotificationsPlugin();

  // 配置FlutterLocalNotificationsPlugin(同上)
  // ...

  configureSelectNotificationSubject(flutterLocalNotificationsPlugin);

  runApp(MyApp());
}

这个示例展示了如何使用simple_local_notifications插件来发送本地通知,并处理用户与通知的交互。请确保根据实际需求调整代码,如通知ID、标题、内容以及通道设置等。

回到顶部