小编典典

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

flutter

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

有一个案例pulling a list有2个数据(isPullingStatedataList),我怎么能避免生成控件DataList控件的一部分时dataList没有变化,但构建部件部分isPullingState,从改变
假的

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


阅读 290

收藏
2020-08-13

共1个答案

小编典典

BlocBuilder有optinal参数condition具有类型bool Function(State previous, State current),你需要返回true,如果你想了Widget调用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);
          },
        ),
      ],
    );
  }
2020-08-13