Flutter通知管理插件at_notify_flutter的使用

Flutter通知管理插件at_notify_flutter的使用

概览

at_notify_flutter 包是为希望在 atProtocol 应用中处理通知的 Flutter 开发者设计的。该开源包用 Dart 编写,支持 Flutter,并遵循 atPlatform 的去中心化、边缘计算模型,具有以下功能:

  • 通过个人数据存储对数据访问进行加密控制
  • 不需要应用后端
  • 端到端加密,只有数据所有者拥有密钥
  • 私人且无监控的连接
  • 发送和接收通知

我们称之为“翻转互联网”,让用户控制对其数据的访问。更多关于其工作原理的信息可以阅读 atPlatform 文档

入门指南

有三种方法可以开始使用此包。

1. 快速启动 - 使用 at_app 生成一个骨架应用

该包包含一个在 <a href="https://github.com/atsign-foundation/at_widgets/tree/trunk/packages/at_notify_flutter/example" rel="ugc">Example</a> 目录中的工作示例应用,你可以使用 at_app create 在四个命令内创建一个个性化的副本。

$ flutter pub global activate at_app
$ at_app create --sample=<package ID> <app name>
$ cd <app name>
$ flutter run

注意:

  1. 只需要运行一次 flutter pub global activate
  2. 使用 at_app.bat 适用于 Windows

2. 从 GitHub 克隆

你可以自由地克隆源代码来自 <a href="https://github.com/atsign-foundation/at_widgets" rel="ugc">GitHub 仓库</a>。那里包含的示例代码与上面提到的模板相同。

$ git clone https://github.com/atsign-foundation/at_widgets.git

3. 手动将包添加到项目中

有关如何手动将此包添加到你的项目的说明可以在 pub.dev 上找到。

开始使用

首先,你需要阅读 atPlatform 文档 来获取 SDK 的基本概述。

要使用此包,你必须有一个基本设置。按照这里的步骤 开始设置

如何工作

设置

预期应用程序将首先使用注册向导验证一个 atsign

通知服务需要使用 atClientManager、当前 AtSignatClientPreference 进行初始化。

initializeNotifyService(
      atClientManager,
      activeAtSign,
      atClientPreference,
    );

该包需要本地通知权限:

iOS: (ios/Runner/AppDelegate.swift)

if #available(iOS 10.0, *) {
  UNUserNotificationCenter.current().delegate = self as? UNUserNotificationCenterDelegate
}

Android: (android/app/src/main/AndroidManifest.xml)

android:showWhenLocked="true"
android:turnScreenOn="true"

使用

要向 atsign 发送消息的通知:

notifyText(
      context,
      currentAtsign,
      receiver,
      message,
    )

要查看过去的通知列表:

Navigator.push(
    context,
    MaterialPageRoute(
        builder: (context) =>
            NotifyScreen(notifyService: NotifyService())),
  );

开源使用和贡献

这是开源代码,所以你可以自由地使用它,提出修改或增强建议,或者创建自己的版本。详细的指导信息可以在 CONTRIBUTING.md 中找到。

示例代码

以下是完整的示例代码,演示了如何使用 at_notify_flutter 插件。

import 'dart:async';

import 'package:at_app_flutter/at_app_flutter.dart' show AtEnv;
import 'package:at_client_mobile/at_client_mobile.dart';
import 'package:at_notify_flutter_example/second_screen.dart';
import 'package:at_onboarding_flutter/at_onboarding_flutter.dart'
    show AtOnboarding, AtOnboardingConfig, AtOnboardingResultStatus;
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart' show getApplicationSupportDirectory;

Future<void> main() async {
  await AtEnv.load();
  runApp(const MyApp());
}

Future<AtClientPreference> loadAtClientPreference() async {
  var dir = await getApplicationSupportDirectory();
  return AtClientPreference()
    ..rootDomain = AtEnv.rootDomain
    ..namespace = AtEnv.appNamespace
    ..hiveStoragePath = dir.path
    ..commitLogPath = dir.path
    ..isLocalStoreRequired = true;
}

final StreamController<ThemeMode> updateThemeMode = StreamController<ThemeMode>.broadcast();

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

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

class _MyAppState extends State<MyApp> {
  // * load the AtClientPreference in the background
  Future<AtClientPreference> futurePreference = loadAtClientPreference();
  AtClientPreference? atClientPreference;

  [@override](/user/override)
  Widget build(BuildContext context) {
    return StreamBuilder<ThemeMode>(
      stream: updateThemeMode.stream,
      initialData: ThemeMode.light,
      builder: (BuildContext context, AsyncSnapshot<ThemeMode> snapshot) {
        ThemeMode themeMode = snapshot.data ?? ThemeMode.light;
        return MaterialApp(
          // * The onboarding screen (first screen)
          theme: ThemeData().copyWith(
            brightness: Brightness.light,
            primaryColor: const Color(0xFFf4533d),
            colorScheme: ThemeData.light().colorScheme.copyWith(
                  primary: const Color(0xFFf4533d),
                  surface: Colors.white,
                ),
            scaffoldBackgroundColor: Colors.white,
          ),
          darkTheme: ThemeData().copyWith(
            brightness: Brightness.dark,
            primaryColor: Colors.blue,
            colorScheme: ThemeData.dark().colorScheme.copyWith(
                  primary: Colors.grey[850],
                ),
            scaffoldBackgroundColor: Colors.grey[850],
          ),
          themeMode: themeMode,
          home: Scaffold(
            appBar: AppBar(
              title: const Text('MyApp'),
              actions: <Widget>[
                IconButton(
                  onPressed: () {
                    updateThemeMode.sink.add(themeMode == ThemeMode.light ? ThemeMode.dark : ThemeMode.light);
                  },
                  icon: Icon(
                    Theme.of(context).brightness == Brightness.light
                        ? Icons.dark_mode_outlined
                        : Icons.light_mode_outlined,
                  ),
                )
              ],
            ),
            body: Builder(
              builder: (context) => Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    ElevatedButton(
                      onPressed: () async {
                        var preference = await futurePreference;
                        setState(() {
                          atClientPreference = preference;
                        });
                        if (context.mounted) {
                          final result = await AtOnboarding.onboard(
                            context: context,
                            config: AtOnboardingConfig(
                              atClientPreference: atClientPreference!,
                              domain: AtEnv.rootDomain,
                              rootEnvironment: AtEnv.rootEnvironment,
                              appAPIKey: AtEnv.appApiKey,
                            ),
                          );
                          switch (result.status) {
                            case AtOnboardingResultStatus.success:
                              Navigator.push(context, MaterialPageRoute(builder: (_) => const SecondScreen()));
                              break;
                            case AtOnboardingResultStatus.error:
                              ScaffoldMessenger.of(context).showSnackBar(
                                const SnackBar(
                                  backgroundColor: Colors.red,
                                  content: Text('An error has occurred'),
                                ),
                              );
                              break;
                            case AtOnboardingResultStatus.cancel:
                              break;
                          }
                        }
                      },
                      child: const Text('Onboard an atSign'),
                    ),
                    const SizedBox(height: 10),
                    ElevatedButton(
                      onPressed: () async {
                        var preference = await futurePreference;
                        atClientPreference = preference;
                        if (context.mounted) {
                          AtOnboarding.reset(
                            context: context,
                            config: AtOnboardingConfig(
                              atClientPreference: atClientPreference!,
                              domain: AtEnv.rootDomain,
                              rootEnvironment: AtEnv.rootEnvironment,
                              appAPIKey: AtEnv.appApiKey,
                            ),
                          );
                        }
                      },
                      child: const Text('Reset'),
                    ),
                  ],
                ),
              ),
            ),
          ),
        );
      },
    );
  }
}

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

1 回复

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


当然,以下是一个关于如何在Flutter项目中使用at_notify_flutter插件进行通知管理的代码示例。at_notify_flutter是一个假设存在的Flutter插件,用于处理通知。由于具体的插件API和方法可能会根据插件的版本和文档有所不同,以下代码示例将基于常见的Flutter插件使用模式进行编写。

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

dependencies:
  flutter:
    sdk: flutter
  at_notify_flutter: ^x.y.z  # 替换为实际的版本号

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

接下来,在你的Flutter项目中,你可以按照以下步骤使用at_notify_flutter插件来管理通知。

1. 初始化插件

在你的main.dart文件或者任何合适的位置初始化插件:

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // 初始化通知插件
    AtNotifyFlutter.instance.init();

    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('At Notify Flutter Demo'),
        ),
        body: NotificationDemo(),
      ),
    );
  }
}

2. 配置通知权限和通道

AndroidiOS平台上,你需要配置通知权限和通道。以下是一个简化的配置示例:

Android (AndroidManifest.xml)

确保在AndroidManifest.xml中请求必要的权限:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.VIBRATE"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>

iOS (Info.plist)

Info.plist中添加必要的通知权限请求:

<key>UIBackgroundModes</key>
<array>
    <string>remote-notification</string>
</array>
<key>UNNotificationBreakthroughPriority</key>
<true/>
<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

3. 发送本地通知

使用at_notify_flutter插件发送本地通知:

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

class NotificationDemo extends StatefulWidget {
  @override
  _NotificationDemoState createState() => _NotificationDemoState();
}

class _NotificationDemoState extends State<NotificationDemo> {

  void sendLocalNotification() {
    AtNotifyFlutter.instance.sendLocalNotification(
      title: "Hello",
      body: "This is a local notification!",
      channelId: "default_channel", // 确保在平台上已创建此通道
      payload: "custom_data",
      // 其他可选参数,如icon, sound等
    );
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: ElevatedButton(
        onPressed: sendLocalNotification,
        child: Text("Send Local Notification"),
      ),
    );
  }
}

4. 处理通知点击事件

为了处理用户点击通知时的事件,你可以监听插件提供的回调:

@override
void initState() {
  super.initState();

  // 监听通知点击事件
  AtNotifyFlutter.instance.onNotificationClicked.listen((notification) {
    // 处理通知点击事件
    print("Notification clicked: ${notification.payload}");
    // 你可以在这里导航到应用内的特定页面
  });
}

请注意,上述代码是一个简化的示例,具体实现可能会因插件的API和平台差异而有所不同。务必查阅at_notify_flutter插件的官方文档以获取最新的API和配置指南。

由于at_notify_flutter是一个假设的插件名称,如果它实际上不存在,你可能需要查找一个类似的Flutter通知管理插件,如flutter_local_notifications,并参考其文档进行实现。

回到顶部