Flutter关注与粉丝管理插件at_follows_flutter的使用

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

Flutter关注与粉丝管理插件at_follows_flutter的使用

插件介绍

at_follows_flutter 是一个为 atSign 提供基本社交“follows”功能的 Flutter 插件。该插件提供了跟随和被跟随列表,并且可以取消跟随某个 atSign。

版本信息

功能特性

  • 提供跟随和取消跟随的功能。
  • 管理跟随者列表和被跟随列表。

开始使用

要开始使用此插件,请访问 atSign 文档以了解 atProtocol 和其相关包的基本设置:atsign docs

Android 设置

在 AndroidManifest.xml 中添加以下权限:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.USE_FULL_SCREEN_INTENT" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-feature android:name="android.hardware.camera.flash" />

同时,在 app/build.gradle 中更新 Android 版本支持:

compileSdkVersion 229 // And above

minSdkVersion 224
targetSdkVersion 229 // And above

iOS 设置

在 info.plist 中添加以下权限字符串:

&lt;key&gt;NSCameraUsageDescription&lt;/key&gt;
&lt;string&gt;The camera is used to scan QR code to pair your device with your atSign&lt;/string&gt;

同时,在 Podfile 中添加以下代码:

post_install do do |installer|
  installer.pods_project.targets.each do |target|
    flutter_additional_ios_build_settings(target)
    target.build_configurations.each do |config|
      config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] ||= [
        '$(inherited)',
        ## dart: PermissionGroup.calendar
        'PERMISSION_EVENTS=0',

        ## dart: PermissionGroup.reminders
        'PERMISSION_REMINDERS=0',

        ## dart: PermissionGroup.contacts
        'PERMISSION_CONTACTS=0',

        ## dart: PermissionGroup.microphone
        'PERMISSION_MICROPHONE=0',

        ## dart: PermissionGroup.speech
        'PERMISSION_SPEECH_RECOGNIZER=0',

        ## dart: [PermissionGroup.location, PermissionGroup.locationAlways, PermissionGroup.locationWhenInUse]
        'PERMISSION_LOCATION=0',

        ## dart: PermissionGroup.notification
        'PERMISSION_NOTIFICATIONS=0',

        ## dart: PermissionGroup.sensors
        'PERMISSION_SENSORS=0'
      ]
    end
  end
end

示例代码

下面是一个完整的示例代码,展示了如何使用 at_follows_flutter 插件来实现基本的跟随和取消跟随功能。

import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart' show getApplicationSupportDirectory;

import 'services/at_service.dart';

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
    // TODO set the rest of your AtClientPreference here
  ;
}

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

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

class _MyAppState extends State<MyApp> {
  Future<AtClientPreference> futurePreference = loadAtClientPreference();
  AtClientPreference? atClientPreference;
  AtAuthService? atClientService;

  final AtSignLogger _logger = AtSignLogger(AtEnv.appNamespace);

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      navigatorKey: NavService.navKey,
      home: Scaffold(
        appBar: AppBar(
          title: const Text('at_follows_flutter example app'),
        ),
        body: Builder(
          builder: (context) {
            return Column(
              children: [
                SizedBox(height: 25),
                Center(
                  child: ElevatedButton(
                    onPressed: () async {
                      var preference = await futurePreference;
                      setState(() {
                        atClientPreference = preference;
                      });
                      final result = await AtOnboarding.onboard(
                        context: context,
                        config: AtOnboardingConfig(
                          appAPIKey: '477b-876u-bcez-c42z-6a3d',
                          atClientPreference: atClientPreference!,
                          rootEnvironment: AtEnv.rootEnvironment,
                          domain: AtEnv.rootDomain,
                        ),
                      );
                      switch (result.status) {
                        case AtOnboardingResultStatus.success:
                          final atsign = result.atsign;

                          AtService.getInstance().atClientServiceInstance =
                              AtClientMobile.authService(atsign!, atClientPreference!);

                          await AtClientManager.getInstance()
                              .setCurrentAtSign(atsign, atClientPreference!.namespace!, atClientPreference!);
                          await Navigator.pushReplacement(
                            context,
                            MaterialPageRoute(
                              builder: (context) {
                                return NextScreen();
                              },
                            ),
                          );
                          break;
                        case AtOnboardingResultStatus.error:
                          _logger.severe('Onboarding throws ${result.errorCode} error');
                          await showDialog(
                            context: context,
                            builder: (BuildContext context) {
                              return AlertDialog(
                                content: const Text('Something went wrong'),
                                actions: [
                                  TextButton(
                                    onPressed: () {
                                      Navigator.of(context).pop();
                                    },
                                    child: const Text('ok')),
                                ],
                              );
                            },
                          );
                          break;
                        default:
                      }
                    },
                    child: const Text('Start onboarding'),
                  ),
                ),
                SizedBox(height: 25),
                Center(
                  child: TextButton(
                    style: ButtonStyle(
                      backgroundColor: MaterialStateProperty.all<Color>(Colors.black12),
                    ),
                    onPressed: () async {
                      var _atsignsList = await KeychainUtil.getAtsignList();
                      for (String atsign in (_atsignsList ?? [])) {
                        await KeychainUtil.resetAtSignFromKeychain(atsign);
                      }

                      ScaffoldMessenger.of(context)
                        .showSnackBar(const SnackBar(content: Text('Cleared all paired atsigns')));
                    },
                    child: const Text('Clear paired atsigns', style: TextStyle(color: Colors.black)),
                  ),
                ),
              ],
            );
          },
        ),
      ),
    );
  }
}

class NavService {
  static GlobalKey&lt;NavigatorState&gt; navKey = GlobalKey();
}

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

1 回复

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


当然,以下是如何在Flutter项目中集成和使用at_follows_flutter插件进行关注与粉丝管理的代码示例。这个插件通常用于社交应用,允许用户关注其他用户并管理他们的关注列表和粉丝列表。

首先,确保你的Flutter项目已经创建并且你已经添加了必要的依赖项。

1. 添加依赖项

在你的pubspec.yaml文件中添加at_follows_flutter依赖项:

dependencies:
  flutter:
    sdk: flutter
  at_follows_flutter: ^最新版本号  # 替换为实际的最新版本号

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

2. 配置插件

根据插件的文档,你可能需要进行一些额外的配置,比如初始化服务。这通常涉及到在main.dart中设置一些初始化代码。

3. 使用插件

以下是一个简单的示例,展示了如何使用at_follows_flutter插件进行关注与粉丝管理:

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Follows Management Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: FollowsScreen(),
    );
  }
}

class FollowsScreen extends StatefulWidget {
  @override
  _FollowsScreenState createState() => _FollowsScreenState();
}

class _FollowsScreenState extends State<FollowsScreen> {
  final AtFollowsPlugin atFollowsPlugin = AtFollowsPlugin();

  String? currentUser = "current_user_id";  // 替换为当前用户的ID
  String? targetUser = "target_user_id";  // 替换为目标用户的ID

  @override
  void initState() {
    super.initState();
    // 初始化插件(如果需要)
    // atFollowsPlugin.init();
  }

  void handleFollow() async {
    try {
      bool isFollowed = await atFollowsPlugin.followUser(currentUser!, targetUser!);
      print("Follow result: $isFollowed");
      // 更新UI或执行其他操作
    } catch (e) {
      print("Error following user: $e");
    }
  }

  void handleUnfollow() async {
    try {
      bool isUnfollowed = await atFollowsPlugin.unfollowUser(currentUser!, targetUser!);
      print("Unfollow result: $isUnfollowed");
      // 更新UI或执行其他操作
    } catch (e) {
      print("Error unfollowing user: $e");
    }
  }

  void handleGetFollows() async {
    try {
      List<String> follows = await atFollowsPlugin.getFollows(currentUser!);
      print("Follows: $follows");
      // 更新UI或执行其他操作
    } catch (e) {
      print("Error getting follows: $e");
    }
  }

  void handleGetFollowers() async {
    try {
      List<String> followers = await atFollowsPlugin.getFollowers(currentUser!);
      print("Followers: $followers");
      // 更新UI或执行其他操作
    } catch (e) {
      print("Error getting followers: $e");
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Follows Management'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            TextButton(
              onPressed: handleFollow,
              child: Text('Follow User'),
            ),
            TextButton(
              onPressed: handleUnfollow,
              child: Text('Unfollow User'),
            ),
            TextButton(
              onPressed: handleGetFollows,
              child: Text('Get My Follows'),
            ),
            TextButton(
              onPressed: handleGetFollowers,
              child: Text('Get My Followers'),
            ),
          ],
        ),
      ),
    );
  }
}

注意事项

  1. 替换用户ID:确保将currentUsertargetUser替换为实际的用户ID。
  2. 错误处理:在实际应用中,你应该有更健壮的错误处理机制。
  3. UI更新:在调用插件方法后,你可能需要更新UI以反映最新的关注/粉丝状态。
  4. 插件初始化:某些插件可能需要额外的初始化步骤,请参考插件的官方文档。

这段代码提供了一个基本的框架,展示了如何使用at_follows_flutter插件进行关注与粉丝管理。根据你的应用需求,你可能需要扩展或修改这些功能。

回到顶部