flutter_bloc的BlocBuilder是否可以避免重建未更改的Widget部分?

时间:2019-07-14 05:44:01

标签: flutter bloc

flutter_bloc中的

BlocBuilder是将页面的所有状态放在一起的一种。

在某种情况下,pulling a list有2个数据(isPullingStatedataList),当dataList不变但构建窗口小部件时,如何避免构建dataList的窗口小部件部分isPullingState的一部分从 true 更改为 false 吗?

BlocBuilderCondition看起来仅在孔状态不变时才避免重建。

1 个答案:

答案 0 :(得分:1)

BlocBuilder具有类型为condition的最佳参数bool Function(State previous, State current),如果您希望小部件调用true函数,则需要返回builder,和false(如果您不愿意)。此参数是可选的,默认情况下为true

由于在condition参数中您具有previous状态和current状态,因此您可以比较这些状态的属性,并在满足条件的情况下返回true比较。

请记住,您需要覆盖状态及其状态类中使用的所有类的==运算符和hashCode。简便的方法是使用equatable

根据您的情况,您需要像这样的State

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,
        ]);
}

然后在窗口小部件中,可以设置所需的条件:

@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);
          },
        ),
      ],
    );
  }