Flutter BLoC - How to pass parameter to event?
Asked Answered
B

1

17

Trying to learn BLoCs I came up with this problem. I have some code in which I generate some buttons with BLoC pattern. However, I have no clue how to update specific buttons properties with dispatch(event) method. How to pass parameters to the event ChangeSomeValues??

The part where the BLoC is used

BlocBuilder(
  bloc: myBloc,
  builder: (context, state) {
    return ListView.builder(
      itemCount: state.buttonList.length,
      itemBuilder: (context, index) {
        return MyButton(
          label: buttonList[index].label,
          value: buttonList[index].value,
          onPressed: myBloc.dispatch(ChangeSomeValues()),
        );
      }
    );
  }
),

MyBloc.dart

class MyBloc extends Bloc<MyEvent, MyState> {

  @override
  Stream<MyState> mapEventToState(MyEvent event) async* {
    if (event is ChangeSomeValues) {
      ... modify specific parameters in list here ...
      yield MyState1(modifiedList);
    }
  }
}

I know how to use the events to change values but I couldn't find how to edit specific parameters in list with this kind of a generic implementation.

Berte answered 4/7, 2019 at 10:28 Comment(3)
i dont get it: you dont know how to pass a parameter to ChangeSomeValues() constructor?Spickandspan
It's an event. If I pass some parameters to the constructor how will that if clause work?Berte
if (event is ChangeSomeValues) { ? of courseSpickandspan
V
32

Code for your event :

class ChangeSomeValues extends MyEvent {
  final int data;

  ChangeSomeValues(this.data);
}

dispatch it as : myBloc.dispatch(ChangeSomeValues(15))

The bloc

class MyBloc extends Bloc<MyEvent, MyState> {

  @override
  Stream<MyState> mapEventToState(MyEvent event) async* {
    if (event is ChangeSomeValues) {
      print("here's the data : ${event.data}");
    }
  }
}
Vadnee answered 4/7, 2019 at 16:3 Comment(2)
Great! Do you know why those builder generated buttons won't update when clicked? After hot reload I see the updated states but not beforeBerte
Figured it out: I had to change state into something else and then back to update the BlocBuilderBerte

© 2022 - 2024 — McMap. All rights reserved.