简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM