flutter_bloc 的 BlocBuilder 是否可以避免重建 Widget 中没有变化的部分?

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

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

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

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

BlocBuilder 有一个类型为 bool Function(State previous, State current) 的可选参数 condition,如果你想让小部件调用 return true =16=] 函数,如果你不想要,可以使用 false。该参数可选,默认为true.

因为在 condition 参数中你有 previous 状态和 current 状态你可以比较这个状态和 return true 如果它满足你的比较。

请记住,您需要覆盖您所在州的 == 运算符和 hashCode 以及您所在州 class 中使用的所有 classes。简单的方法是使用 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);
          },
        ),
      ],
    );
  }