Flutter BLoC - How to pass parameter to event?

非 Y 不嫁゛ 提交于 2020-07-08 15:25:12

问题


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.


回答1:


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}");
    }
  }
}


来源:https://stackoverflow.com/questions/56885956/flutter-bloc-how-to-pass-parameter-to-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!