Flutter通知管理插件notix的使用

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

Flutter通知管理插件Notix的使用

目录

安装

在你的 pubspec.yaml 文件中添加以下行:

dependencies:
  notix: ^x.y.z

x.y.z 替换为 pub.dev 上的最新版本。

开始使用

1. 初始化Notix

初始化Notix并设置配置,例如Firebase Cloud Messaging (FCM) 设置和通知渠道。这是在应用程序中使用Notix之前必不可少的步骤。

import 'package:Notix/Notix.dart';

void main() async {
  await Notix.init(
    configs: NotixConfig(
      firebaseMessagingKey: 'YOUR_FCM_API_KEY',
      icon: 'notification_icon',
      // 添加更多配置选项
    ),
  );
}
2. 获取clientNotificationId

要通过FCM接收通知,目标用户必须具有由FCM为每个设备生成的唯一ID,即clientNotificationId。根据用户登录的设备数量,用户可能有多个clientNotificationIds。

Notix提供了轻松获取该ID的方法,并且你需要将其存储在用户数据中,以便稍后向该用户发送通知。

你可以通过调用 Notix.getToken() 或监听 Notix.onTokenRefresh 流来获取令牌。

/// 获取FCM令牌
Notix.getToken().then((value) {
  if (value == null) return;
  MyDatasource.addNewFCMToken(
    userId: 'user_id',
    clientNotificationId: value,
  );
});

/// 监听FCM令牌
Notix.onTokenRefresh.listen((event) {
  MyDatasource.addNewFCMToken(
    userId: 'user_id',
    clientNotificationId: value,
  );
});
3. 发送通知

轻松地向你的应用程序用户发送通知。你可以自定义每条通知的内容、渠道和行为。

void sendNotification() {
  NotixMessage notification = NotixMessage(
    title: '新消息',
    body: '你有一条新消息。',
    clientNotificationIds: ['unique_id'],
    // 添加更多通知详情
  );

  Notix.push(notification, addToHistory: true);
}
4. 查看用户的通知历史记录

假设你熟悉Firebase Firestore,那么通知会存储在Firestore中,因此你可以在应用程序中的通知屏幕中显示它们。

Notix已经提供了简单的Firestore查询,剩下的工作就交给你了,你可以按自己的方式定制屏幕。建议使用 kr_paginate_firestore 来构建UI,使用以下查询:

  1. 首先,Notix需要知道当前用户的ID,可以通过以下方式定义:
await Notix.init(
  configs: NotixConfig(
    // ...
    currentUserId: () => _authController.currentUser.id,
  ),
);
  1. 当向用户发送通知时,设置接收者的用户ID:
final notification = NotixMessage(
  targetedUserId: 'user_id',
  // ...
);
  1. 显示通知历史记录
import 'package:kr_paginate_firestore/paginate_firestore.dart';

KrPaginateFirestore(
  itemBuilder: (context, documentSnapshots, i) {
    NotixMessage not = documentSnapshots.elementAt(i).data() as NotixMessage;
    return NotificationCard(not);
  },
  query: Notix.firebaseQuery(),
  itemBuilderType: PaginateBuilderType.listView,
  isLive: true,
  onEmpty: Center(
    child: Padding(
      padding: const EdgeInsets.only(bottom: 140),
      child: const EmptyWidget(text: '尚无通知'),
    ),
  ),
  initialLoader: const Column(
    children: [
      NotificationCardEmpty(),
      NotificationCardEmpty(),
      NotificationCardEmpty(),
    ],
  ),
  bottomLoader: const NotificationCardEmpty(),
)

当用户与通知交互或离开通知屏幕时,不要忘记标记通知为已读。

Notix.markAsSeen('notification_id');

你也可以通过将 addToHistory 设置为 false 来推送通知而不将其添加到通知历史记录中。

Notix.push(notification, addToHistory: false);

进阶用法

1. 通知渠道

Notix支持在Android上创建和管理通知渠道。你可以定义具有不同行为(如声音、振动或LED颜色)的渠道。

NotixChannel channel = NotixChannel(
  id: 'chat',
  name: '聊天',
  description: '聊天频道',
  playSound: true,
  showBadge: true,
  enableVibration: true,
  enableLights: true,
  ledColor: Colors.blue,
  sound: 'custom_sound.mp3',
  importance: NotixImportance.high,
);

// 将渠道添加到配置
NotixConfig configs = NotixConfig(
  channels: [
    channel,
    // 其他渠道
  ],
  // ...
);

await Notix.push(
  NotixMessage(
    // ...
    channel: 'chat',
  ),
);

你也可以通过定义组渠道来分组通知:

final channel = NotixChannel(
  id: 'chat',
  name: '聊天',
  // ...
  // 设置groupId
  groupId: 'chat_group',
);

final groupChannel = NotixGroupChannel(
  id: 'chat_group',
  name: '聊天',
  description: '聊天频道',
),

// 将渠道添加到配置
NotixConfig configs = NotixConfig(
  channels: [channel],
  groupChannels: [groupChannel],
  // ...
);

await Notix.push(
  NotixMessage(
    title: '新消息',
    body: '你有一条新消息。',
    clientNotificationIds: ['unique_id'],
    channel: 'chat',
  ),
);
2. 处理推送通知事件

处理传入的通知并自定义用户与其交互时的行为。你可以监听各种通知事件并采取相应操作。

你可以通过以下两种方式处理通知事件:

  1. 在配置中设置 onSelectNotificationonRecievedNotification
await Notix.init(
  configs: NotixConfig(
    firebaseMessagingKey: 'YOUR_FCM_API_KEY',
    icon: 'notification_icon',
    onSelectNotification: (notification) {
      if (notification.type == 'message') {
        Navigator.of(context).pushNamed('/chat');
      }
    },
    onRecievedNotification: (notification) {
      print(notification.payload);
    },
  ),
);
  1. 或者通过监听 eventsStream
import 'package:Notix/Notix.dart';

void main() {
  Notix.eventsStream.listen((event) {
    switch (event.type) {
      case EventType.receiveNotification:
        // 处理单个通知接收事件。
        break;
      case EventType.notificationTap:
        // 处理通知点击事件。
        break;
      case EventType.notificationAdd:
        // 处理通知添加事件。
        break;
    }
  });
}
3. 自定义通知

目前所有通知都只有一种样式,即标题和可选正文。不支持图片和自定义布局。但是,你可以配置通知图标、声音和重要性。

通知将采用相关的通道的一般配置。你可以在 NotixMessage 模型中覆盖这些配置:

final notification = NotixMessage(
  // ...
  importance: NotixImportance.high,
  isSeen: true,
  playSound: true,
)
4. 向多个设备发送通知

FCM主题消息允许你向订阅了特定主题的所有设备发送消息。为了将通知推送到主题,请设置主题ID而不是 clientNotificationIds

await Notix.push(
  NotixMessage(
    title: '新消息',
    body: '你有一条新消息。',
    topic: 'topic_id',
    channel: 'chat',
  ),
);

然后你需要订阅该主题:

await Notix.subscibeToTopic('topic_id');

你也可以取消订阅特定主题:

await Notix.unsubscibeToTopic('topic_id');

或者取消订阅所有主题:

await Notix.unsubscribeFromAll();
5. 定时发送通知

要定时发送通知,只需在 NotixMessage 模型中添加 scheduleTime

final notification = NotixMessage(
  // ...
  scheduleTime: ScheduleTime(
    sendAt: DateTime(2024, 2, 1),
    timeZone: 'Asia/Baghdad', // 可选(默认值为设备时区)
  ),
);
6. 根据特定条件显示通知

你可以根据你的逻辑决定是否显示或忽略推送通知。例如,在聊天应用中,如果接收者已经在同一个聊天室中,你可能不想推送通知。

await Notix.init(
  // ...
  canShowNotification: (notification) {
    return currentOpenedChat != notification.payload?['chatId'];
  },
);
7. 添加负载到通知

假设你有一个邀请模型,并希望将邀请数据与通知一起发送,并在接收方端检索此数据。可以使用 payload 参数分配你的模型数据,并使用 toMapfromMap 方法进行数据转换。

class InviteModel {
  final String id;
  final DateTime date;
  final String title;

  InviteModel({
    required this.id,
    required this.date,
    required this.title,
  });

  InviteModel.fromMap(Map<String, dynamic> map)
      : id = map['id'],
        date = DateTime.parse(map['date']),
        title = map['title'];

  Map<String, dynamic> toMap() => {
        'id': id,
        'date': date.toString(),
        'title': title,
      };
}

Notix.init(
  configs: NotixConfig(
    // ...
    onSelectNotification: (notification) {
      switch (notification.payload?['type']) {
        case 'invite':
          {
            final invite = InviteModel.fromMap(notification.payload!);
            Navigator.push(
              Get.context!,
              MaterialPageRoute(
                builder: (context) => InviteScreen(invite),
              ),
            );
          }
          break;
        case 'otherType':
          // ...
          break;
        default:
      }
    },
  ),
);  

final invite = InviteModel(
  id: '1',
  date: DateTime.now(),
  title: '邀请',
);

Notix.push(NotixMessage(
  // ...
  payload: {
    ...invite.toMap(),
    'type': 'invite',
  },
));
8. 自定义数据库

如果你不喜欢使用Firestore?你仍然可以使用Notix与自己的数据源。你可以扩展 NotixDatastore

class CustomNotixDatasource extends NotixDatastore {

  // 你的数据源
  final yourDatastore;

  @override
  Future<NotixMessage?> get(String id) async {
    Map<String, dynamic> data = await yourDatastore.getNotification(id);
    return NotixMessage.fromMap(data);
  }

  @override
  Future<void> delete(String id) async {
    await yourDatastore.deleteNotification(id);
  }

  @override
  Future<void> save(NotixMessage notification) async {
    await yourDatastore.saveNotification(notification.toMap());
  }

  @override
  Future<void> markAsSeen(String notificationId) async {
    await yourDatastore.markNotificationAsSeen(notificationId);
  }

  @override
  Future<void> markAllAsSeen([String? userId]) async {
    await yourDatastore.markAllNotificationsAsSeen(userId);
  }

  @override
  Query<NotixMessage> query([String? userId]) =>
      throw UnimplementedError('The Firestore data source is disabled');

  @override
  Stream<int> get unseenCountStream =>
      throw UnimplementedError('The Firestore data source is disabled');
}

然后你需要在初始化方法中添加你的自定义数据源:

await Notix.init(
  configs: NotixConfig(
    datasourceConfig: CustomNotixDatasource(),
  )
)

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

1 回复

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


当然,下面是一个关于如何在Flutter中使用notix插件进行通知管理的代码示例。notix是一个用于管理本地通知的Flutter插件,它提供了丰富的API来处理通知的创建、更新和取消等操作。

首先,确保你已经在pubspec.yaml文件中添加了notix依赖:

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

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

接下来,我们来看一个基本的代码示例,展示如何使用notix来创建和显示本地通知。

1. 初始化Notix

在你的主文件中(通常是main.dart),初始化Notix服务:

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

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  Notix.initialize(); // 初始化Notix
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomeScreen(),
    );
  }
}

2. 创建通知

在你的HomeScreen组件中,添加按钮来创建通知:

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

class HomeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Notix Example'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () async {
            // 创建通知
            await Notix.show(
              title: 'Hello',
              body: 'This is a notification!',
              payload: 'notification_payload', // 可选的payload,用于识别通知
            );
          },
          child: Text('Show Notification'),
        ),
      ),
    );
  }
}

3. 处理通知点击事件

如果你希望在用户点击通知时执行某些操作,你可以监听Notix的点击事件:

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

class HomeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    Notix.onSelectNotification((String? payload) async {
      // 处理通知点击事件
      if (payload == 'notification_payload') {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('Notification clicked!')),
        );
      }
    });

    return Scaffold(
      appBar: AppBar(
        title: Text('Notix Example'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () async {
            // 创建通知
            await Notix.show(
              title: 'Hello',
              body: 'This is a notification!',
              payload: 'notification_payload', // 可选的payload,用于识别通知
            );
          },
          child: Text('Show Notification'),
        ),
      ),
    );
  }
}

4. 更新和取消通知

你还可以更新或取消已经显示的通知:

// 更新通知
Notix.update(
  id: 'notification_id', // 通知的唯一标识符
  title: 'Updated Title',
  body: 'This notification has been updated!',
);

// 取消通知
Notix.cancel('notification_id');

请注意,在实际使用中,你需要为每个通知分配一个唯一的id,以便能够正确地更新或取消它。在创建通知时,可以通过id参数来指定这个唯一标识符。

这是一个简单的示例,展示了如何在Flutter应用中使用notix插件进行通知管理。根据你的具体需求,你可以进一步自定义和扩展这些功能。

回到顶部