You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Flutter中借助Appwrite获取已关注用户的推文

实现仅获取已关注用户推文的Appwrite方案

核心思路

先获取当前用户的所有被关注用户ID列表,再用这个列表作为筛选条件,查询推文集合中对应用户发布的内容,同时可按需包含当前用户自己的推文。

步骤实现(以JavaScript SDK为例)

1. 获取当前用户的关注列表

假设你有一个follows集合,每个文档存储followerId(关注者ID)和followingId(被关注者ID):

// 获取当前用户关注的所有用户ID
const getFollowingIds = async (currentUserId) => {
  const followDocs = await databases.listDocuments(
    '<你的数据库ID>',
    '<你的follows集合ID>',
    [Query.equal('followerId', currentUserId)]
  );
  return followDocs.documents.map(doc => doc.followingId);
};

2. 查询已关注用户的推文

假设推文集合为tweets,每个文档包含userId(发布者ID)、content(推文内容)、createdAt(发布时间)等字段:

// 获取已关注用户(含自己)的推文
const getFollowedTweets = async (currentUserId) => {
  const followingIds = await getFollowingIds(currentUserId);
  // 加入当前用户ID,显示自己的推文(可选,按需移除)
  const targetIds = [...followingIds, currentUserId];

  const tweets = await databases.listDocuments(
    '<你的数据库ID>',
    '<你的tweets集合ID>',
    [
      Query.equal('userId', targetIds), // 筛选目标用户的推文
      Query.orderDesc('createdAt'),    // 按发布时间倒序排列
      Query.limit(20)                  // 分页限制,按需调整
    ]
  );

  return tweets.documents;
};

优化建议

  • 添加索引:给tweets集合的userId字段添加索引,大幅提升查询速度,尤其是关注用户较多时。
  • 分页处理:如果推文数量大,结合Query.cursorAfter()实现滚动加载,示例:
    // 带分页的查询
    const getFollowedTweetsWithPagination = async (currentUserId, cursor = null) => {
      const followingIds = await getFollowingIds(currentUserId);
      const targetIds = [...followingIds, currentUserId];
    
      const queries = [
        Query.equal('userId', targetIds),
        Query.orderDesc('createdAt'),
        Query.limit(20)
      ];
    
      if (cursor) {
        queries.push(Query.cursorAfter(cursor)); // 基于上一页最后一条文档的ID分页
      }
    
      return await databases.listDocuments('<你的数据库ID>', '<你的tweets集合ID>', queries);
    };
    
  • 权限控制:确保tweets集合的权限设置符合需求,比如公开推文允许所有已登录用户读取,私密推文仅允许关注者读取(可通过Appwrite的文档权限规则配置)。

内容的提问来源于stack exchange,提问作者Zionnite

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 11:12:43