我正在尝试理解 block 语句解决方案。但我不明白 buildWhen
真正的用途是什么。当值为 true 时,它将返回 if if 条件的第一个语句。那么 buildWhen
有何用途?
示例是:
BlocBuilder<OrdersBloc, OrdersState>(
buildWhen: (context, state) {
return state is OrdersState.OrderCompleted
},
builder: (context, state) {
if (state is OrdersState.OrderCompleted) {
return Container(child: Text('Order Completed!'));
} else if (OrdersState.OrderInProgress) {
return Container(child: Text('In Progress'));
} else if (OrdersState.OrderRequested) {
return Container(child: Text('A customer placed an order!'));
} else {
return Container(child: Text('Waiting for an order'));
}
},
);
最佳答案
为了对何时调用构建器函数进行细粒度控制,可以提供可选的 buildWhen。 buildWhen 获取前一个 block 状态和当前 block 状态并返回一个 bool 值。 如果 buildWhen 返回 true,则将使用状态调用构建器,并且小部件将重建。如果 buildWhen 返回 false,则不会使用状态调用构建器,并且不会发生重建。
BlocBuilder<BlocA, BlocAState>(
buildWhen: (previousState, state) {
// return true/false to determine whether or not
// to rebuild the widget with state
},
builder: (context, state) {
// return widget here based on BlocA's state
}
)
关于flutter - block 中 buildWhen 的用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69257662/