flutterblocflutter-bloccubit

Does Bloc Rebuild (BlocBuilder) The Whole Widget Tree When New State emitted?


I encountered an issue when I wrapped my MaterialApp widget in a BlocBuilder. I expected the entire widget tree to rebuild whenever a new state was emitted. However, I noticed that some widgets didn’t rebuild as expected.

Here’s a simplified example:

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return BlocBuilder<MyCubit, MyState>(
      builder: (context, state) {
        return MaterialApp(
          theme: state.isDarkMode ? ThemeData.dark() : ThemeData.light(),
          home: const MyHomePage(),
        );
      },
    );
  }
}

class MyHomePage extends StatelessWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Home')),
      body: const Center(child: Text('Hello, world!')),
    );
  }
}

In this setup:

What I Tried

To solve the problem, I wrapped the specific widgets that didn’t rebuild (e.g., MyHomePage) in another BlocBuilder, like this:

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return BlocBuilder<MyCubit, MyState>(
      builder: (context, state) {
        return Scaffold(
          appBar: AppBar(title: Text(state.isDarkMode ? 'Dark Mode' : 'Light Mode')),
          body: Center(child: Text(state.isDarkMode ? 'Dark Mode On' : 'Light Mode On')),
        );
      },
    );
  }
}

This approach worked, but now I’m wondering:

  1. Is the reason some widgets didn’t rebuild initially because they were marked as const?
  2. Or is it because BlocBuilder only rebuilds its immediate children, and deeper widgets are unaffected?
  3. Is wrapping widgets in multiple BlocBuilders the best practice, or is there a better way to handle this?

I’d appreciate insights or recommendations!


Solution

  • Whatever is below BlocBuilder will be rebuild. Solution:: Wrap whatever items requires rebuild with BlocBuilder. There can be more than one BlocBuilder in the same widget tree.

    Also you can can control rebuild using buildWhen parameter in blocbuilder