Can BlocBuilder of flutter_bloc avoid rebuild part

2019-08-19 00:36发布

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.

标签: flutter bloc
1条回答
时光不老,我们不散
2楼-- · 2019-08-19 01:27

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);
          },
        ),
      ],
    );
  }
查看更多
登录 后发表回答