Asim Bhadra
Asim Bhadra

Reputation: 318

Flutter - How to rebuild Widget with Bloc?

I am new to Bloc pattern in flutter and I am trying to understand this code here, I have a widget as:

Widget forumList() {
    return BlocProvider<ForumBloc>(
      create: (context) => ForumBloc(ForumService())..add(GetAllForumPosts()),
      child: BlocBuilder<ForumBloc, ForumState>(
        builder: (context, state) {
          if (state is ForumLoading) {
            return Text('Loading');
          }
          if (state is ForumLoaded) {
            var posts = state.forumPosts;
            return ListView.separated(
              shrinkWrap: true,
              physics: NeverScrollableScrollPhysics(),
              padding: const EdgeInsets.symmetric(vertical: 8),
              itemCount: posts.length,
              itemBuilder: (context, index) {
                var post = posts[index];
                return ForumPostCard(
                  forumModel: post,
                  onPressed: () {
                    Navigator.pushNamed(context, Routes.forumDetails,
                        arguments: {'post': post});
                  },
                );
              },
              separatorBuilder: (context, index) => SizedBox(height: 5),
            );
          }
          return SizedBox();
        },
      ),
    );
  }

Now how can I rebuild this widget after clicking a button?

Upvotes: 1

Views: 6942

Answers (1)

Omatt
Omatt

Reputation: 10463

If you just need to rebuild the screen, calling setState() should trigger a rebuild.

BlocBuilder on the other hand rebuilds on state changes. If there's a state change that you'd like to observe in your bloc, calling something like context.read<ForumBloc>().doSomething() should update the widgets inside BlocBuilder.

Using BlocListener is another approach that you can use.

Upvotes: 3

Related Questions