Same BLoC event not triggering more than one time
Asked Answered
L

2

5

I've HomeBloc from HomeView class. Basic UI architecture is as following:

HomeView extends StatelessWidget {
    BlocProvider( child: HomeBody(), bloc: new HomeBloc() )
}

HomeBody extends StatefulWidget {
    createState => HomeBodyState()
}

HomeBodyState extends State {
    BlocBuilder(
        bloc: BlocProvider.of<HomeBloc>()
        child: Container(
            child: Column(
                children: [
                    BlocProvider( child: CashFlowView, bloc: new HomeBloc() )
                ]
            )
        )
    )
}

CashFlowView extends StatefulWidget {
    createState => CashFlowState()
}

CashFlowState extends State {
    BlocBuilder(
        bloc: BlocProvider.of<HomeBloc>()
        child: Container(
            child: Column(
                children: [
                    ChipGroupWidget(
                      onClick => BlocProvider.of().add(event) //  <----- Problem is here
                    )
                ]
            )
        )
    )
}

Whole code can be found in this repository. Problem is when any Chip inside my ChipGroup is tapped, a callback function is called in CashFlowState. Inside that, a bloc event is added to bloc with some data. But it is triggering only for first time. What's wrong in my code?

Longhorn answered 4/8, 2020 at 14:41 Comment(0)
V
4

From the bloc library documentation
Extend your state class with equatable and after each event emit a new state (same type) with the new properyties (data)

Vespucci answered 5/1, 2021 at 15:27 Comment(0)
E
2

In flutter bloc pattern system, the UI is rebuilt only when the state changes. If in any case when a fired event triggers the same state currently the bloc is in, the build function won't be called again, i.e, the UI won't be rebuilt.

In your case, when for the first time the CashFlowState is yielded, the whole code works just fine. But then the same state is yielded again, the event is triggered, but the build function isn't being called again, because the state never changed.

What you have to do is, create two different states along with two different events. Lets say, chipTappedEvent will yield chipTappedState, and chipResetEvent will yield chipResetState.

In the beginning you can use chipResetState or any other state as initial state. Then when the user taps on a chip, just trigger the chipTappedEvent which should yield chipTappedState.

In your listener, listen for the state chipTappedState and do what you have to do. Then immediately trigger the chipResetEvent which should yield chipResetState. In this way, when the user taps the chip again, the yielded state will be chipTappedState which will be different from chipResetState, so the build function will be called again.

Ezequieleziechiele answered 5/8, 2020 at 6:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.