Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter nested cubit not getting recreated

Tags:

flutter

bloc

I have a flutter app using BLoC architecture with the flutter_bloc package.

Part of my widget tree looks like this:

class ItemsWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.max,
      children: [
        BlocBuilder<FirstCubit, FirstState>(
          builder: (context, state) {
            return Expanded(
              child: ListView.builder(
                  itemCount: state.items.length,
                  itemBuilder: (context, index) {
                    Item item = state.items[index];
                    return BlocProvider<SecondCubit>(
                      create: (_) => SecondCubit(item),
                      child: ItemWidget(),
                    );
                  },
                ),
              );
            },
        ),
      ],
    );
  }
}

So, the FirstCubit's state FirstState contains a list of Items. Inside the BlocBuilder, I have got another BlocProvider for the ItemWidget, because this widget depends on the SecondCubit's state, that contains an Item. Now, when the FirstCubit's state changes, I want to rebuild the whole widget tree. Because the items could change completely, I want to recreate all the SecondCubits as well. But here is my problem: The create function of the nested BlocProviders only gets called when the BlocBuilder first gets build, but doesn't get called on the rebuilds. Is that a wanted behavior? How can I change that?

like image 609
Apri Avatar asked May 05 '26 19:05

Apri


1 Answers

Give your ListView.builder a key, something like ListView.builder(key: UniqueKey()), and every time BlocBuilder rebuilds the widget tree, it will force the ListView to be rebuilt.

like image 143
Tung Ha Avatar answered May 07 '26 14:05

Tung Ha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!