Flutter通知管理插件d2d_notifications的使用

Flutter通知管理插件d2d_notifications的使用

使用Firebase Cloud进行整个应用程序,并且没有自定义服务器? 是否曾经想从客户端(用户应用)发送通知? D2D Notification是一个一站式解决方案,可以在一个设备到另一个设备之间触发/发送FCM推送通知,而无需任何服务器。

平台支持

此插件仅用于通过HTTP触发/发送通知请求。它不处理任何有关Firebase Messaging(接收推送通知)的操作。

Android iOS MacOS Web Linux Windows
发送自 ✔️ ✔️ ✔️ ✔️ ✔️ ✔️

使用

要使用此插件,请在pubspec.yaml文件中添加d2d_notifications作为依赖项。

初始化d2d_notification服务并提供serverKey

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  D2DNotification(serverKey: "YOUR_SERVER_KEY"); // 在main()中添加此行。
  runApp(const MyApp());
}

生成通知请求参数

参数to可以包含一个主题(TOPIC)或FCM令牌(FCM TOKEN)。

Firebase为我们提供了一个主题的概念。订阅该特定主题的所有用户都能收到发送给该主题的通知。

主题示例

假设用户订阅了名为dogs的主题:

D2DNotificationRequest request = D2DNotificationRequest(
  to: "dogs",
  title: "这是标题",
  subtitle: "这是副标题",
  body: "这是正文",
  imageUrl: "https://picsum.photos/200/300",
  data: {
    "key 1": value1,
    ...
    "key 2": "value2"
  },
);

// 发送通知请求并接收响应。
D2DNotificationTopicResponse? response = await D2DNotification.instance.sendNotificationToTopic(request);
if (response != null) {
  print("通知发送成功。${response.messageId}");
}

每次安装应用程序时,Firebase都会为用户设备上的应用程序实例生成一个唯一的FCM令牌。要针对单个用户,您可以使用此令牌。您需要该用户的FCM令牌。

令牌示例

假设用户具有FCM令牌xyz

D2DNotificationRequest request = D2DNotificationRequest(
  to: "xyz",
  title: "这是标题",
  subtitle: "这是副标题",
  body: "这是正文",
  imageUrl: "https://picsum.photos/200/300",
  data: {
    "key 1": value1,
    ...
    "key 2": "value2"
  },
);

// 发送通知请求并接收响应。
D2DNotificationTokenResponse? response = await D2DNotification.instance.sendNotificationToToken(request);
if (response != null) {
  print("通知发送成功。${response.results}");
}

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

1 回复

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


d2d_notifications 是一个用于在 Flutter 应用中管理通知的插件。它可以帮助开发者轻松地创建、显示和管理通知。以下是如何使用 d2d_notifications 插件的基本步骤:

1. 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  d2d_notifications: ^1.0.0  # 请使用最新版本

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

2. 初始化插件

在你的 Flutter 应用中,首先需要初始化 d2d_notifications 插件。

import 'package:d2d_notifications/d2d_notifications.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  // 初始化通知插件
  await D2DNotifications.initialize();
  
  runApp(MyApp());
}

3. 请求通知权限

在显示通知之前,你需要请求用户的通知权限。

void requestNotificationPermission() async {
  final status = await D2DNotifications.requestPermission();
  if (status == NotificationPermission.granted) {
    print('通知权限已授予');
  } else {
    print('通知权限被拒绝');
  }
}

4. 显示通知

你可以使用 D2DNotifications.showNotification 方法来显示通知。

void showNotification() async {
  await D2DNotifications.showNotification(
    id: 1,
    title: '测试通知',
    body: '这是一个测试通知的内容',
    payload: 'notification_payload',
  );
}

5. 处理通知点击事件

你可以通过监听通知的点击事件来处理用户点击通知后的操作。

void listenToNotificationClicks() {
  D2DNotifications.onNotificationClick.stream.listen((payload) {
    print('通知被点击,payload: $payload');
    // 在这里处理通知点击事件
  });
}

6. 取消通知

你可以通过 D2DNotifications.cancelNotification 方法来取消已经显示的通知。

void cancelNotification() async {
  await D2DNotifications.cancelNotification(1);
}

7. 完整示例

以下是一个完整的示例,展示了如何使用 d2d_notifications 插件来请求权限、显示通知和处理通知点击事件。

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

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  // 初始化通知插件
  await D2DNotifications.initialize();
  
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: NotificationExample(),
    );
  }
}

class NotificationExample extends StatefulWidget {
  [@override](/user/override)
  _NotificationExampleState createState() => _NotificationExampleState();
}

class _NotificationExampleState extends State<NotificationExample> {
  [@override](/user/override)
  void initState() {
    super.initState();
    requestNotificationPermission();
    listenToNotificationClicks();
  }

  void requestNotificationPermission() async {
    final status = await D2DNotifications.requestPermission();
    if (status == NotificationPermission.granted) {
      print('通知权限已授予');
    } else {
      print('通知权限被拒绝');
    }
  }

  void showNotification() async {
    await D2DNotifications.showNotification(
      id: 1,
      title: '测试通知',
      body: '这是一个测试通知的内容',
      payload: 'notification_payload',
    );
  }

  void listenToNotificationClicks() {
    D2DNotifications.onNotificationClick.stream.listen((payload) {
      print('通知被点击,payload: $payload');
      // 在这里处理通知点击事件
    });
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('通知管理示例'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: showNotification,
          child: Text('显示通知'),
        ),
      ),
    );
  }
}
回到顶部