[英]Can BlocBuilder of flutter_bloc avoid rebuild part of Widget which not changing?
BlocBuilder
of flutter_bloc
is kind of put all state of page together. flutter_bloc
BlocBuilder
是将页面的所有状态放在一起的一种。
There's a case for pulling a list
there's 2 data ( isPullingState
, dataList
), how can I avoid build widget part of dataList when dataList
not change, but build widget part of isPullingState
which changed from true to false ? 有一个
pulling a list
的情况是有2个数据( isPullingState
, dataList
),当dataList
不变时,如何避免构建dataList的小部件部分,而是将isPullingState
构建小部件部分从true更改为false ?
BlocBuilderCondition
looks like only avoid rebuild when hole state not change. BlocBuilderCondition
看起来仅当孔状态不变时才避免重建。
The BlocBuilder
have a optinal parameter condition
that have type bool Function(State previous, State current)
, you need to return true
if you want the widget call the builder
function, and false
if you don't want. BlocBuilder
具有最佳参数condition
,其condition
类型为bool Function(State previous, State current)
,如果要让小部件调用builder
函数,则需要返回true
如果不想,则需要返回false
。 This parameter is optional, and by default is true
. 此参数是可选的,默认情况下为
true
。
Because the in the condition
parameter you have the previous
state and the current
state you can compare the properties of this states and and return true
if it satisfies your comparisons. 因为
condition
参数中的您具有previous
状态和current
状态,所以您可以比较此状态的属性,并在满足比较条件时返回true
。
Remember that you need to override the ==
operator and hashCode
of your state and all classes that use in your state class. 请记住,您需要覆盖状态以及状态类中使用的所有类的
==
运算符和hashCode
。 And easy way to do this is using equatable . 简单的方法是使用equatable 。
In your case you need to have a State
like this: 在您的情况下,您需要具有以下
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,
]);
}
And then in your widget you can set the condition that you want: 然后,您可以在小部件中设置所需的条件:
@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);
},
),
],
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.