Flutter消息推送管理插件firebase_notification_scheduler的使用

Flutter 消息推送管理插件 firebase_notification_scheduler 的使用

安装

pubspec.yaml 文件中添加 firebase_notification_scheduler 作为依赖项。

dependencies:
  firebase_notification_scheduler: ^0.0.2

如何使用

创建 API 密钥
  1. 注册并获取 Firebase Notification Scheduler Rapid API 的 API 密钥 在这里
  2. 创建您的认证密钥 在这里
初始化包
final FirebaseNotificationScheduler firebaseNotificationScheduler =  
    FirebaseNotificationScheduler(  
        authenticationKey: '<YOUR-RAPID-API-KEY>', 
        rapidApiKey: '<YOUR-AUTHENTICATION-KEY>'
    );
调度通知
// 调度通知到主题 'any',下一分钟发送
final String _payload = {
  "to": "/topics/any",
  "notification": {
    "title": "标题",
    "body": "内容"
  },
  "data": {"key_1": "值1", "key_2": "值2"}
}.toString();
final DateTime _now = DateTime.now().toUtc();
final DateTime _dateTimeInUtc = _now.add(const Duration(minutes: 1));

await firebaseNotificationScheduler.scheduleNotification(
    payload: _payload, dateTimeInUtc: _dateTimeInUtc);
获取所有调度的通知
List<ScheduledNotification> list = await firebaseNotificationScheduler.getAllScheduledNotification();
取消通知
firebaseNotificationScheduler.cancelNotification(messageId: 'k3821Fq0jQ0U-sDXp');

示例代码

以下是一个完整的示例代码,展示了如何使用 firebase_notification_scheduler 插件来调度、获取和取消通知。

import 'package:flutter/material.dart';
import 'package:firebase_notification_scheduler/firebase_notification_scheduler.dart';
import 'package:intl/intl.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Firebase Notification Scheduler',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Firebase Notification Scheduler'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  [@override](/user/override)
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  // 在这里填写您的 API 密钥和认证密钥
  final FirebaseNotificationScheduler firebaseNotificationScheduler =
      FirebaseNotificationScheduler(authenticationKey: '<YOUR-RAPID-API-KEY>', rapidApiKey: '<YOUR-AUTHENTICATION-KEY>');

  late Future<List<ScheduledNotification>> getScheduledNotificationFuture;

  [@override](/user/override)
  void initState() {
    super.initState();
    getScheduledNotificationFuture =
        firebaseNotificationScheduler.getAllScheduledNotification();
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('FNS 示例'),
      ),
      body: _body(),
    );
  }

  Widget _body() {
    return SingleChildScrollView(
      child: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Expanded(child: _scheduleNotificationWidget()),
                const SizedBox(
                  width: 10,
                ),
                Expanded(child: _getScheduledNotificationsButton()),
              ],
            ),
            const Divider(),
            const Text(
              '您的已调度通知',
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
            _scheduledNotificationList()
          ],
        ),
      ),
    );
  }

  Widget _scheduleNotificationWidget() {
    final String _payload = {
      "to": "/topics/any",
      "notification": {
        "title": "标题",
        "body": "内容"
      },
      "data": {"key_1": "值1", "key_2": "值2"}
    }.toString();
    final DateTime _now = DateTime.now().toUtc();
    final DateTime _dateTimeInUtc = _now.add(const Duration(minutes: 1));

    return ElevatedButton.icon(
        onPressed: () async {
          debugPrint('正在调度新的通知');
          await firebaseNotificationScheduler.scheduleNotification(
              payload: _payload, dateTimeInUtc: _dateTimeInUtc);
          getScheduledNotificationFuture =
              firebaseNotificationScheduler.getAllScheduledNotification();
          setState(() {});
        },
        icon: const Icon(Icons.add),
        label: const Text('调度至下一分钟'));
  }

  Widget _scheduledNotificationList() {
    return FutureBuilder(
        future: getScheduledNotificationFuture,
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return const CircularProgressIndicator();
          }
          if (snapshot.hasData) {
            List<ScheduledNotification> data =
                snapshot.data as List<ScheduledNotification>;

            if (data.isEmpty) {
              return const Center(child: Text('无已调度的通知'));
            }

            return ListView.separated(
                separatorBuilder: (c, i) => const Divider(),
                itemCount: data.length,
                shrinkWrap: true,
                itemBuilder: (buildContext, index) {
                  ScheduledNotification item = data[index];
                  bool isQueued = item.status.contains('QUEUED') ||
                      item.status.contains('READY');
                  return ListTile(
                    title: Text('计划于 ' +
                        DateFormat.yMMMMd().add_jm().format(item.sendAt)),
                    subtitle: Text('状态 ' + item.status),
                    trailing: isQueued
                        ? TextButton(
                            child: const Text('取消'),
                            onPressed: () async {
                              await firebaseNotificationScheduler
                                  .cancelNotification(messageId: item.messageId);
                              firebaseNotificationScheduler
                                  .getAllScheduledNotification();
                              setState(() {});
                            },
                          )
                        : const SizedBox(
                            width: 0,
                          ),
                  );
                });
          }
          if (snapshot.hasError) {
            return Text(
                "无法获取您的已调度通知\n 错误: ${snapshot.error}");
          }

          return const Text("无数据");
        });
  }

  Widget _getScheduledNotificationsButton() {
    return ElevatedButton.icon(
      onPressed: () {
        getScheduledNotificationFuture =
            firebaseNotificationScheduler.getAllScheduledNotification();
        setState(() {});
      },
      icon: const Icon(Icons.refresh),
      label: const Text("刷新通知列表"),
      style:
          ButtonStyle(backgroundColor: MaterialStateProperty.all(Colors.green)),
    );
  }
}

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

1 回复

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


firebase_notification_scheduler 是一个 Flutter 插件,用于在特定时间安排 Firebase 云消息(FCM)推送通知。这个插件允许你在应用中以编程方式设置通知的发送时间,而不是依赖服务器端来调度通知。

以下是如何使用 firebase_notification_scheduler 插件的基本步骤:

1. 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  firebase_core: latest_version
  firebase_messaging: latest_version
  firebase_notification_scheduler: latest_version

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

2. 初始化 Firebase

在使用 Firebase 服务之前,你需要初始化 Firebase。通常在你的 main.dart 文件中进行初始化。

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

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

3. 配置 Firebase Cloud Messaging

你需要在 firebase_messaging 中配置 Firebase Cloud Messaging (FCM) 以接收推送通知。

import 'package:firebase_messaging/firebase_messaging.dart';

final FirebaseMessaging _firebaseMessaging = FirebaseMessaging.instance;

void configureFirebaseMessaging() {
  _firebaseMessaging.requestPermission();

  FirebaseMessaging.onMessage.listen((RemoteMessage message) {
    print("onMessage: $message");
  });

  FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
    print("onMessageOpenedApp: $message");
  });

  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
}

Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  print("Handling a background message: ${message.messageId}");
}

4. 使用 firebase_notification_scheduler 安排通知

现在你可以使用 firebase_notification_scheduler 来安排通知。

import 'package:firebase_notification_scheduler/firebase_notification_scheduler.dart';

void scheduleNotification() async {
  // 设置通知的调度时间
  DateTime scheduledTime = DateTime.now().add(Duration(minutes: 5));

  // 创建通知内容
  NotificationDetails notificationDetails = NotificationDetails(
    android: AndroidNotificationDetails(
      'channel_id',
      'channel_name',
      'channel_description',
      importance: Importance.max,
      priority: Priority.high,
    ),
    iOS: IOSNotificationDetails(),
  );

  // 调度通知
  await FirebaseNotificationScheduler().schedule(
    scheduledTime: scheduledTime,
    notificationDetails: notificationDetails,
    payload: 'custom_payload',
  );

  print('Notification scheduled for $scheduledTime');
}

5. 处理通知点击

你可以在应用启动时处理通知点击事件。

void handleNotificationClick() async {
  final initialMessage = await FirebaseMessaging.instance.getInitialMessage();
  if (initialMessage != null) {
    print("Notification clicked: ${initialMessage.data}");
  }
}

6. 完整示例

以下是一个完整的示例,展示了如何在 Flutter 应用中使用 firebase_notification_scheduler 插件。

import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:firebase_notification_scheduler/firebase_notification_scheduler.dart';
import 'package:flutter/material.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  configureFirebaseMessaging();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Firebase Notification Scheduler'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            scheduleNotification();
          },
          child: Text('Schedule Notification'),
        ),
      ),
    );
  }
}

void configureFirebaseMessaging() {
  final FirebaseMessaging _firebaseMessaging = FirebaseMessaging.instance;

  _firebaseMessaging.requestPermission();

  FirebaseMessaging.onMessage.listen((RemoteMessage message) {
    print("onMessage: $message");
  });

  FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
    print("onMessageOpenedApp: $message");
  });

  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
}

Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  print("Handling a background message: ${message.messageId}");
}

void scheduleNotification() async {
  DateTime scheduledTime = DateTime.now().add(Duration(minutes: 5));

  NotificationDetails notificationDetails = NotificationDetails(
    android: AndroidNotificationDetails(
      'channel_id',
      'channel_name',
      'channel_description',
      importance: Importance.max,
      priority: Priority.high,
    ),
    iOS: IOSNotificationDetails(),
  );

  await FirebaseNotificationScheduler().schedule(
    scheduledTime: scheduledTime,
    notificationDetails: notificationDetails,
    payload: 'custom_payload',
  );

  print('Notification scheduled for $scheduledTime');
}
回到顶部