Flutter本地通知插件flutter_local_notifications_windows的使用

发布于 1周前 作者 bupafengyu 来自 Flutter

Flutter本地通知插件flutter_local_notifications_windows的使用

flutter_local_notifications_windowspackage:flutter_local_notifications 的 Windows 实现,作为 FFI 包,可以在纯 Dart 或 Flutter 插件中运行。参见 Dart 的 FFI 文档

限制

  • 不支持重复通知:Windows 不支持重复的通知,因此调用 <code>periodicallyShow</code><code>periodicallyShowWithDuration</code> 方法会抛出 <code>UnsupportedError</code> 异常。
  • 仅允许具有包标识的应用获取先前显示的通知:这意味着在未打包为 MSIX 安装程序的应用中,<code>cancel</code> 操作无效,并且 <code>getActiveNotifications</code> 将返回一个空列表。要将您的应用打包为 MSIX,请参阅 <code>package:msix</code><code>msix</code> 部分在 example 的 pubspec.yaml 中。

项目结构

此模板使用以下结构:

  • src:包含本机源代码及用于构建该源代码为动态库的 CMake 文件。在此文件夹中,有三个 C++ 文件:

    • <code>ffi_api.h</code>/<code>ffi_api.cpp</code>:一个与 C 兼容的头文件,其中包含 Dart 将使用的 API 及其 C++ 实现。
    • <code>plugin.hpp</code>/<code>plugin.cpp</code>:一个持有 <a href="https://learn.microsoft.com/en-us/windows/uwp/cpp-and-winrt-apis/">C++/WinRT</a> SDK 句柄的 C++ 类,以及一些 Windows 专用逻辑。<code>ffi_api.cpp</code> 使用此类实现其功能。
    • <code>utils.hpp</code>/<code>utils.cpp</code>:处理从 C 结构到 WinRT 类型的数据复制和分配。由于 FFI 是通过基于 C 的 API 进行的,C++ 类型如字符串、映射和向量需要进行转换。
  • lib:包含定义插件 API 的 Dart 代码,并使用 <code>dart:ffi</code> 调用本机代码。

    • <code>details</code> 文件夹包含所有 Windows 特定的通知配置,如 <code>WindowsAction</code><code>WindowsImage</code> 等。
    • <code>ffi</code> 文件夹包含生成的绑定(参见下文)和其他 FFI 工具。
    • <code>plugin</code> 文件夹以两种方式实现 <code>package:flutter_local_notifications_platform_interface</code>:一种是不支持 FFI 的平台的存根,另一种是基于 FFI 的实现。
  • windows 文件夹包含用于构建和捆绑本机代码库与平台应用程序的构建文件。

构建和捆绑本机代码

src 中的代码可以通过 CMake 构建。包括一个 <code>build.bat</code> 文件,其代码如下:

@echo off
cd build
cmake ../windows
cmake --build .
cd ..
copy build\shared\Debug\flutter_local_notifications_windows.dll .

这将从本机代码生成 DLL 并将其复制到当前目录。这对于在没有 Flutter 的情况下本地测试非常有用。当使用 Flutter 时,此步骤是不必要的,因为 Flutter 会为您构建并捆绑资产。

绑定到本机代码

为了使用本机代码,需要在 Dart 中创建绑定。为了避免手动编写这些绑定,它们是从头文件 <code>src/ffi_api.h</code><code>package:ffigen</code> 自动生成的。重新生成绑定可以通过运行 <code>dart run ffigen --config ffigen.yaml</code> 来完成。

示例代码

以下是使用 flutter_local_notifications_windows 插件的完整示例代码:

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

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

  // 初始化 flutter_local_notifications
  final flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();

  // 设置初始化设置
  const AndroidInitializationSettings initializationSettingsAndroid =
      AndroidInitializationSettings('app_icon');

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

  await flutterLocalNotificationsPlugin.initialize(initializationSettings);

  runApp(MyApp(flutterLocalNotificationsPlugin));
}

class MyApp extends StatelessWidget {
  final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin;

  MyApp(this.flutterLocalNotificationsPlugin);

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('Flutter Local Notifications Example')),
        body: Center(
          child: ElevatedButton(
            onPressed: () async {
              // 创建并显示本地通知
              const AndroidNotificationDetails androidPlatformChannelSpecifics =
                  AndroidNotificationDetails(
                      'your channel id', 'your channel name',
                      importance: Importance.max,
                      priority: Priority.high,
                      showWhen: true);

              const NotificationDetails platformChannelSpecifics =
                  NotificationDetails(android: androidPlatformChannelSpecifics);

              await flutterLocalNotificationsPlugin.show(
                0,
                'Test Notification',
                'This is a test notification',
                platformChannelSpecifics,
                payload: 'item x',
              );
            },
            child: Text('Show Notification'),
          ),
        ),
      ),
    );
  }
}

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

1 回复

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


当然,下面是一个关于如何在Flutter项目中使用flutter_local_notifications_windows插件来实现本地通知的示例代码。这个插件允许你在Windows平台上发送本地通知。

1. 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  flutter_local_notifications: ^9.0.0  # 请确保使用最新版本

dev_dependencies:
  flutter_test:
    sdk: flutter

flutter:
  plugin:
    platforms:
      windows:
        pluginClass: FlutterLocalNotificationsPlugin

dependencies_override:
  flutter_local_notifications_windows:
    path: ../path_to_your_fork_or_local_copy_of_flutter_local_notifications_windows  # 如果你从本地路径引入,可以添加这一行,否则直接使用上面的版本控制

注意:dependencies_override部分通常用于从本地路径引入插件,如果你直接从pub.dev安装,则不需要这一部分。

2. 配置Windows插件

windows/runner/CMakeLists.txt中,确保你有以下配置来链接必要的库(通常这一步在插件安装时自动完成):

# Flutter Local Notifications Windows
add_subdirectory(${CMAKE_SOURCE_DIR}/../flutter_local_notifications_windows flutter_local_notifications_windows)
target_link_libraries(runner PRIVATE flutter_local_notifications_windows)

3. 初始化通知插件

在你的Flutter应用的main.dart文件中,初始化通知插件并配置它:

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

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

  const InitializationSettings initializationSettings = InitializationSettings(
    windows: const WindowsInitializationSettings()
  );

  flutterLocalNotificationsPlugin.initialize(initializationSettings, onInitializationComplete: (status) {
    if (!status['didInitialize']) {
      // Initialization failed
    }
  });

  runApp(MyApp());
}

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

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

              var iosChannel = const IOSNotificationChannel(
                'high_importance_channel', // id
                'High Importance Notifications', // title
                'This channel is used for important notifications.', // description
              );

              if (await flutterLocalNotificationsPlugin.resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>()?.createNotificationChannel(androidChannel) == null) {
                // Android channel creation failed
              }

              // iOS specific: apple badge count, sound settings, etc.
              var iosSettings = IOSNotificationSettings(
                sound: true,
                alert: true,
                badge: true
              );

              // Create a notification and show it
              var notification = Notification(
                title: 'Hello',
                body: 'World',
                channelKey: 'high_importance_channel',
              );

              await flutterLocalNotificationsPlugin.show(
                notification.hashCode,
                notification.title,
                notification.body,
                NotificationDetails(
                  android: AndroidNotificationDetails(
                    channel.id,
                    channel.name,
                    channel.description,
                    icon: '@mipmap/ic_launcher',
                  ),
                  iOS: IOSNotificationDetails(
                    presentAlert: true,
                    presentSound: true,
                    presentBadge: true,
                  ),
                ),
              );
            },
            child: Text('Show Notification'),
          ),
        ),
      ),
    );
  }
}

4. 运行应用

确保你的Flutter环境已经设置好,并且Windows开发工具链已经配置完成。然后,你可以通过以下命令运行你的应用:

flutter run -d windows

这个示例代码展示了如何在Flutter应用中初始化并使用flutter_local_notifications_windows插件来发送本地通知。你可以根据需求进一步定制通知的内容和行为。

回到顶部