在 Flutter 中显示帖子列表

问题描述 投票:0回答:1

我有一个社交媒体应用程序,它像任何其他社交媒体应用程序一样显示可垂直滚动的帖子列表。所以问题是功能没有按预期工作,我不知道出了什么问题。我确信有帖子可以显示,但问题可能是用户界面。这就是我从 Firebase 获取帖子所做的事情:

 final postsProvider = FutureProvider.family<List<Post>, model.User>(
      (ref, model.User user) async {
    final friends = user.following;

    final allPosts = await Future.wait(
      friends.map((frId) async {
        final asyncValue = ref.read(postPoolProvider(frId));
        return asyncValue.maybeWhen(
          data: (posts) => posts,
          orElse: () => <Post>[],
        );
      }),
    );

    return allPosts.expand((posts) => posts).toList();
  });

所以基本上我在这里创建一个

FutureProvider
,它接受两个参数
ref
model.User user
并返回帖子列表。
postPoolProvider
用于获取userId对应的用户的所有帖子列表。以下是我如何使用它来构建 UI:
frId

我将上面的小部件称为 
Widget _buildPosts(BuildContext context, model.User user) { final hiddenPosts = ref.watch(hiddenPostsProvider); final postAsyncValue = ref.watch(postsProvider(user)); return postAsyncValue.when( data: (data) { final visiblePosts = data.where((post) => !hiddenPosts.contains(post.id)).toList(); return CustomScrollView( scrollDirection: Axis.vertical, shrinkWrap: true, physics: const NeverScrollableScrollPhysics(), slivers: [ SliverList( delegate: SliverChildBuilderDelegate( (context, index) { if (index != 0 && index % 4 == 0) { final height = MediaQuery.of(context).size.height * 0.6; return _ad != null ? SizedBox(height: height, child: AdWidget(ad: _ad!)) : const SizedBox.shrink(); } else { final postIndex = index - (index ~/ 4); if (postIndex < visiblePosts.length) { return PostCard( id: visiblePosts[postIndex].userId, user: user, index: postIndex); } else { return const SizedBox.shrink(); } } }, childCount: visiblePosts.length + (visiblePosts.length ~/ 3), ), ), ], ); }, error: (error, stack) => _buildErrorScreen(error), loading: () => _buildLoadingScreen(), ); }

的主体。我 100% 确定我的数据库中有帖子,所以问题要么是我在家里获取它们,要么是构建 UI。任何帮助将不胜感激。谢谢

    

flutter firebase dart riverpod
1个回答
0
投票

NestedScrollView

然后在你的 Widget 中,你写道:

import 'package:flutter_riverpod/flutter_riverpod.dart'; part '....'; @riverpod class Posts extends _$Posts { @override Future<List<Post>> build(model.User user) => fetch(); Future<List<Post>> fetch() async { state = const AsyncValue.loading(); final friends = user.following; //note that user is visible everywhere in the class final allPosts = List.empty(growable: true); for (final frId in friends) { final posts = await ref.read(postPoolProvider(frId).future); allPosts.add(posts); } state = await AsyncValue.guard(() => allPosts); return allPosts; } }

你应该使用这些代码行:

final postAsyncValue = ref.watch(postsProvider(user));

_buildWithData(...)

中,你应该放入 _buildPosts(...) 代码,但更简单,看看逻辑 loading-error-load_data 已经写在这个 build() 方法中了。

© www.soinside.com 2019 - 2024. All rights reserved.