Flutter社交云好友列表管理插件locality_social_cloud_friendlist的使用

Flutter社交云好友列表管理插件locality_social_cloud_friendlist的使用

locality_social_cloud_friendlist

一个基于Locality Social Cloud的Flutter插件,它提供了一个基于发布/订阅机制的好友列表系统,用于在用户之间发送和接收好友请求。该插件允许你安全且高效地管理好友列表,使用SHA-256进行主题哈希,并通过发布/订阅机制实现事件驱动更新。

特性

  • 用户之间发送和接收好友请求。
  • 通过发布/订阅架构管理好友列表。
  • 自动注册和跟踪好友列表。
  • 使用SHA-256哈希生成唯一的主题以确保安全性。
  • 轻松检查用户之间的朋友状态。

配置

首先配置你的Locality Social Cloud并输入你的appId和appSecret来连接到云端:

LocalitySocialCloud.configure(appId: '..', appSecret: '...=');

LoggedInUser loggedInUser = (await LocalitySocialCloud.auth('testuser1', 'pwd1')).loggedInUser!;
LocalityUser user1 = loggedInUser.user;
LocalityUser user2 = (await LocalitySocialCloud.auth('testuser2', 'pwd2')).loggedInUser!.user;

使用

获取好友列表

获取用户的FriendList对象:

FriendList friendList1 = FriendListFacade.getFriendListOfUser(user1);
FriendList friendList2 = FriendListFacade.getFriendListOfUser(user2);

如果你希望在UI中展示好友列表,可以使用以下方式:

friendList1.addListener(() {
  // 当好友列表发生更改时触发
  print("这些是好友列表1中的所有好友:");
  for (var friendRequest in friendList1.friendRequests) {
    // 打印每个好友请求
    print(friendRequest);
  }
});

FriendList是一个ThrottledProvider,可以与Provider包一起轻松使用,以展示UI变化。

发送好友请求

假设你想只在尚未发送过好友请求的情况下发送好友请求。你可以使用FriendList的时间线(Timeline)来实现:

friendList1.timeline.whenSynchronized(() {
  // 等待时间线同步完成
  print("现在我们知道了目标用户是否已经是我们的朋友,我们可以发送好友请求如果他不是。");
  if (!friendList1.sentFriendRequestToUser(user2)) {
    print("发送好友请求...");
    FriendListFacade.sendFriendRequest(user1, user2);
  }
});

检查好友关系

你也可以检查他们是否已经互相发送了好友请求:

friendList1.timeline.whenSynchronized(() {
  if (friendList1.isFriendsWithThisUser(user2)) {
    // 如果他们是朋友,则执行某些操作
  }
});

获取所有好友列表

最后,你可以获取所有已经互发了好友请求的用户列表:

friendList1.timeline.whenSynchronized(() {
  List<LocalityUser> friends = friendList1.computeFriends();
});

更多关于Flutter社交云好友列表管理插件locality_social_cloud_friendlist的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter社交云好友列表管理插件locality_social_cloud_friendlist的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter项目中集成并使用locality_social_cloud_friendlist插件的示例代码。请注意,假设locality_social_cloud_friendlist插件已经发布在pub.dev上,并且其API文档已经足够清晰。如果实际情况有所不同,请参考插件的官方文档进行调整。

1. 添加依赖

首先,在你的pubspec.yaml文件中添加对该插件的依赖:

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

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

2. 导入插件

在你的Dart文件中导入插件:

import 'package:locality_social_cloud_friendlist/locality_social_cloud_friendlist.dart';

3. 初始化插件

通常,你需要在应用的某个初始化阶段(例如在main.dart中)初始化插件:

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  
  // 初始化插件
  LocalitySocialCloudFriendlist.instance.init();

  runApp(MyApp());
}

4. 使用插件功能

获取好友列表

class FriendListScreen extends StatefulWidget {
  @override
  _FriendListScreenState createState() => _FriendListScreenState();
}

class _FriendListScreenState extends State<FriendListScreen> {
  List<Friend> _friends = [];

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

  Future<void> _fetchFriends() async {
    try {
      List<Friend> friends = await LocalitySocialCloudFriendlist.instance.getFriendList();
      setState(() {
        _friends = friends;
      });
    } catch (e) {
      print("Error fetching friends: $e");
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Friend List'),
      ),
      body: ListView.builder(
        itemCount: _friends.length,
        itemBuilder: (context, index) {
          Friend friend = _friends[index];
          return ListTile(
            title: Text(friend.name),
            subtitle: Text(friend.status),
          );
        },
      ),
    );
  }
}

class Friend {
  String id;
  String name;
  String status;

  Friend({required this.id, required this.name, required this.status});
}

添加好友

Future<void> _addFriend(String friendId, String friendName) async {
  try {
    bool success = await LocalitySocialCloudFriendlist.instance.addFriend(friendId, friendName);
    if (success) {
      print("Friend added successfully.");
      // 刷新好友列表
      _fetchFriends();
    } else {
      print("Failed to add friend.");
    }
  } catch (e) {
    print("Error adding friend: $e");
  }
}

删除好友

Future<void> _removeFriend(String friendId) async {
  try {
    bool success = await LocalitySocialCloudFriendlist.instance.removeFriend(friendId);
    if (success) {
      print("Friend removed successfully.");
      // 刷新好友列表
      _fetchFriends();
    } else {
      print("Failed to remove friend.");
    }
  } catch (e) {
    print("Error removing friend: $e");
  }
}

5. 完整示例

将上述代码片段组合成一个完整的示例:

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

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  LocalitySocialCloudFriendlist.instance.init();
  runApp(MyApp());
}

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

class FriendListScreen extends StatefulWidget {
  @override
  _FriendListScreenState createState() => _FriendListScreenState();
}

class _FriendListScreenState extends State<FriendListScreen> {
  List<Friend> _friends = [];

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

  Future<void> _fetchFriends() async {
    try {
      List<Friend> friends = await LocalitySocialCloudFriendlist.instance.getFriendList();
      setState(() {
        _friends = friends;
      });
    } catch (e) {
      print("Error fetching friends: $e");
    }
  }

  Future<void> _addFriend(String friendId, String friendName) async {
    try {
      bool success = await LocalitySocialCloudFriendlist.instance.addFriend(friendId, friendName);
      if (success) {
        print("Friend added successfully.");
        _fetchFriends();
      } else {
        print("Failed to add friend.");
      }
    } catch (e) {
      print("Error adding friend: $e");
    }
  }

  Future<void> _removeFriend(String friendId) async {
    try {
      bool success = await LocalitySocialCloudFriendlist.instance.removeFriend(friendId);
      if (success) {
        print("Friend removed successfully.");
        _fetchFriends();
      } else {
        print("Failed to remove friend.");
      }
    } catch (e) {
      print("Error removing friend: $e");
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Friend List'),
        actions: [
          IconButton(
            icon: Icon(Icons.add),
            onPressed: () {
              // 添加好友的逻辑,这里可以弹出一个对话框让用户输入好友ID和名称
              showDialog(
                context: context,
                builder: (context) {
                  return AlertDialog(
                    title: Text('Add Friend'),
                    content: SingleChildScrollView(
                      child: ListBody(
                        children: [
                          TextField(
                            decoration: InputDecoration(labelText: 'Friend ID'),
                          ),
                          TextField(
                            decoration: InputDecoration(labelText: 'Friend Name'),
                          ),
                        ],
                      ),
                    ),
                    actions: [
                      TextButton(
                        onPressed: () {
                          Navigator.of(context).pop();
                        },
                        child: Text('Cancel'),
                      ),
                      TextButton(
                        onPressed: () async {
                          String friendId = // 获取用户输入的ID
                          String friendName = // 获取用户输入的名称
                          await _addFriend(friendId, friendName);
                          Navigator.of(context).pop();
                        },
                        child: Text('Add'),
                      ),
                    ],
                  );
                },
              );
            },
          ),
        ],
      ),
      body: ListView.builder(
        itemCount: _friends.length,
        itemBuilder: (context, index) {
          Friend friend = _friends[index];
          return ListTile(
            title: Text(friend.name),
            subtitle: Text(friend.status),
            trailing: IconButton(
              icon: Icon(Icons.delete),
              onPressed: () {
                _removeFriend(friend.id);
              },
            ),
          );
        },
      ),
    );
  }
}

class Friend {
  String id;
  String name;
  String status;

  Friend({required this.id, required this.name, required this.status});
}

请确保你已经正确配置了插件,并且API的使用符合插件的文档描述。如果插件的API有所不同,请参考其官方文档进行调整。

回到顶部