flutter_bloc的BlocBuilder可以避免重建部分不改变的Widget吗?

2024-01-09

BlocBuilder of flutter_bloc https://pub.dev/packages/flutter_bloc是将页面的所有状态放在一起。

有一个案例pulling a list有 2 个数据(isPullingState, dataList),如何避免构建 dataList 的小部件部分dataList不改变,但构建小部件的一部分isPullingState其变化自true to false ?

BlocBuilderCondition看起来只有当洞状态没有改变时才避免重建。


The BlocBuilder有一个可选参数condition有类型的bool Function(State previous, State current),你需要返回true如果你想要小部件调用builder函数,以及false如果你不想的话。该参数是可选的,默认为true.

因为在condition参数你有previous国家和current状态您可以比较该状态的属性并返回true如果它满足您的比较。

请记住,您需要覆盖==运算符和hashCode您的状态以及在您的状态类中使用的所有类。简单的方法是使用可等同的 https://github.com/felangel/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);
          },
        ),
      ],
    );
  }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

flutter_bloc的BlocBuilder可以避免重建部分不改变的Widget吗? 的相关文章

随机推荐