BlocBuilder 的 flutter_bloc是将页面的所有状态放在一起。
有一种情况,pulling a list有 2 个数据 ( isPullingState, dataList),如何避免在dataList未更改时构建 dataList 的小部件部分,但构建的小部件部分isPullingState从true变为false?
BlocBuilderCondition 看起来只有在孔状态不变时才避免重建。
Gia*_*ode 13
该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,
]);
}
Run Code Online (Sandbox Code Playgroud)
然后在您的小部件中,您可以设置所需的条件:
@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);
},
),
],
);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4129 次 |
| 最近记录: |