3

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?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.