Showing a list of posts in Flutter

I have a social media app which like any other social media apps shows a list of posts which is vertically scrollable. So the problem is that it the functionality isn’t working as expected and I don’t know what’s wrong. I’m sure there are posts available to show but the problem might be the UI. This is what I have done to fetch posts from Firebase:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code> 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();
});
</code>
<code> 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(); }); </code>
 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();
  });

So basically here I’m creating a FutureProvider which takes in two arguments, ref and model.User user and returns a list of posts. The postPoolProvider is used to get a list of all the post of the user who’s userId corresponds to frId. Here’s how I used this in building the UI:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>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(),
);
}
</code>
<code>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(), ); } </code>
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(),
    );
  }

I called the above widget as a body of a NestedScrollView. I’m 100% certain there are posts in my database so the problem is either with home I’m fetching them or building the UI. Any help will be appreciated. Thanks

I think you should use a listener provider, something like this:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>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;
}
}
</code>
<code>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; } } </code>
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;
  }
}

then in your Widget , where you wrote:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code> final postAsyncValue = ref.watch(postsProvider(user));
</code>
<code> final postAsyncValue = ref.watch(postsProvider(user)); </code>
 final postAsyncValue = ref.watch(postsProvider(user));

you should use these lines of code :

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code> @override
Widget build(BuildContext context, WidgetRef ref) {
final postAsyncValue = ref.watch(postsProvider(user));
return switch (postAsyncValue ) {
AsyncError<List<Post>>(:final error) => _buildErrorScreen(error),
),
AsyncData<List<Post>>(:final value) => _buildWithData(context, ref, value),
_ => _buildLoadingScreen(),
};
}
</code>
<code> @override Widget build(BuildContext context, WidgetRef ref) { final postAsyncValue = ref.watch(postsProvider(user)); return switch (postAsyncValue ) { AsyncError<List<Post>>(:final error) => _buildErrorScreen(error), ), AsyncData<List<Post>>(:final value) => _buildWithData(context, ref, value), _ => _buildLoadingScreen(), }; } </code>
 @override
   Widget build(BuildContext context, WidgetRef ref) {
      final postAsyncValue = ref.watch(postsProvider(user));
     return switch (postAsyncValue ) {
       AsyncError<List<Post>>(:final error) => _buildErrorScreen(error),
         ),
       AsyncData<List<Post>>(:final value) => _buildWithData(context, ref,  value),
       _ =>  _buildLoadingScreen(),
     };
   }
 

in the _buildWithData(…) you should put your _buildPosts(…) code, but simpler, look that the logic loading-error-load_data is already written in this build() method.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật