Can BlocBuilder of flutter_bloc avoid rebuild part of Widget which not changing?

こ雲淡風輕ζ 提交于 2020-01-03 02:31:11

问题


BlocBuilder of flutter_bloc is kind of put all state of page together.

There's a case for pulling a list there's 2 data (isPullingState, dataList), how can I avoid build widget part of dataList when dataList not change, but build widget part of isPullingState which changed from true to false ?

BlocBuilderCondition looks like only avoid rebuild when hole state not change.


回答1:


The BlocBuilder have a optinal parameter condition that have type bool Function(State previous, State current), you need to return true if you want the widget call the builder function, and false if you don't want. This parameter is optional, and by default is true.

Because the in the condition parameter you have the previous state and the current state you can compare the properties of this states and and return true if it satisfies your comparisons.

Remember that you need to override the == operator and hashCode of your state and all classes that use in your state class. And easy way to do this is using equatable.

In your case you need to have a State like this:

class MyState extends Equatable {
  final bool isPullingState;
  final List<MyClass> dataList;

  MyState(this.isPullingState, this.dataList)
      : super([isPullingState, dataList]);
}

class MyClass extends Equatable {
  final int property1;
  final int property2;

  MyClass(this.property1, this.property2)
      : super([
          property1,
          property2,
        ]);
}

And then in your widget you can set the condition that you want:

@override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        BlocBuilder(
          bloc: myBloc,
          condition: (MyState previous, MyState current) =>
              previous.isPullingState != current.isPullingState,
          builder: (BuildContext context, MyState state) {
            // this function is only called when isPullingState change
            return MyIsPullingWidget();
          },
        ),
        BlocBuilder(
          bloc: myBloc,
          condition: (MyState previous, MyState current) =>
              previous.dataList != current.dataList,
          builder: (BuildContext context, MyState state) {
            // this function is only called when the dataList change
            return MyListWidget(state.dataList);
          },
        ),
        BlocBuilder(
          bloc: myBloc,
          builder: (BuildContext context, MyState state) {
            // this function is called in each state change
            return MyListWidget(state.dataList);
          },
        ),
      ],
    );
  }


来源:https://stackoverflow.com/questions/57024903/can-blocbuilder-of-flutter-bloc-avoid-rebuild-part-of-widget-which-not-changing

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