Search code examples
flutterblocflutter-bloc

how pass data from parent to child widget using bloc


what is better ? pass state from parent to children or create each child a builder bloc? (USING PACKAGE flutter_bloc)

BlocProvider(
    create: (context) => ExampleBloc(),
    child: BlocBuilder<ExampleBloc, ExampleState>(
        builder(context, state) {
            return Column(
                children: [
                    Widget1(state.value), <- pass state to prop
                    Widget2(), <- consume the state in bloc builder
                ]
            )
        }
    )
)

//stateless widget
Widget1(state) {
    return Text(state)
}

//stateless widget
Widget2() {
    return BlocBuilder<ExampleBloc, ExampleState>(
        builder: (context, state) {
            return Text(state)
        }
    )
}

Solution

  • Use BlocBuilders. The whole (or at least the biggest) point of Providers is to provide stuff without passing arguments. The clue is in the name. So use the BlocBuilder to pick up the provided state.

    The BlocBuilder will listen to state changes and rebuild when that happens.

    Furthermore, you can add conditions on the BlocBuilder to determine when the widget should be rebuilt, using the buildWhen property. This will very easily optimize the rebuilds.