flutterliststatereloadbloc

Bloc State not reload or updating widget ui when i was emit a list


i try to change listSelctedTest with add/remove function in bloc, but my ui widget not reload/update after emit a listSelectedTest. but, if using ctr+s/hot reload it will change to new value and reload my ui widget.old value = 2 and new value = 2 & 4.

Bloc

void _onChangeTest(OnPriceChangeTest event, var emit) {
final state = this.state;
if (state is PriceChangeTest) {
  try {
    List<String> listSelectedTest = state.copyWith().listSelectedTest ?? [];
    printlog("price change test-1", "$listSelectedTest");
    if (event.selected) {
      listSelectedTest.remove(event.value);
    } else {
      listSelectedTest.add(event.value);
    }
    printlog("price change test-2", listSelectedTest.toString());
    emit(
      state.copyWith(
        listSelectedTest: listSelectedTest,
      ),
    );
  } catch (e) {
    printlog("price change test", e.toString());
  }
}

i was try to using spread operator (...) and List.from(), but nothing has change


Solution

  • In this line:

    List<String> listSelectedTest = state.copyWith().listSelectedTest ?? [];
    

    You're not copying the list, but rather the list is still referring to the same list as the one currently in the state. Replace state.copyWith().listSelectedTest with [...state.listSelectedTest] so that you make sure that the current state won't be affected by the modification done in the next lines with the remove or add method. This will make the states before and after you call emit are actually different so that the widget will rebuild based on the changes.