[英]Changing the bloc of a BlocBuilder depending on a parameter
I have a BlocBuilder which allows me to build a list of elements.我有一个 BlocBuilder,它允许我构建元素列表。 The considered Bloc of the BlocBuilder has in its state the
List<T>
of the elements to be displayed. BlocBuilder 所考虑的 Bloc 在其 state 中包含要显示的元素的
List<T>
。
Now I'd like to use the same BlocBuilder but using a different Bloc to give it a different source for the data (the other Bloc will also hold a List<T>
in its state).现在我想使用相同的 BlocBuilder 但使用不同的 Bloc 为其提供不同的数据源(另一个 Bloc 也将在其状态下保存
List<T>
)。 This new widget will display the information in the exact same way as the other one, the only thing that changes is the content, the data.这个新的小部件将以与另一个小部件完全相同的方式显示信息,唯一改变的是内容,即数据。
The thing is that I don't want to copy/paste my whole BlocBuilder just because the Bloc is different.问题是我不想仅仅因为 Bloc 不同就复制/粘贴我的整个 BlocBuilder。 The only thing thas I have to change is that, instead of
BlocBuilder<BlocA, BlocAState>
, it has to be BlocBuilder<BlocB, BlocBState>
and for that, I don't think that copy/pasting a whole file is worth it.我唯一需要改变的是,它必须是
BlocBuilder<BlocB, BlocBState>
而不是BlocBuilder<BlocA, BlocAState>
<BlocA, BlocBState> ,为此,我认为复制/粘贴整个文件不值得。
I wanted to know if it was possible to change the type of the Bloc just with a ternary operator.我想知道是否可以仅使用三元运算符来更改 Bloc 的类型。 Something like
就像是
bool isTypeA;
BlocBuilder<isTypeA ? BlocA, BlocAState : BlocB, BlocBState>
If I check that before the BlocBuilder, I'll have to copy/paste the whole content which I try to avoid.如果我在 BlocBuilder 之前检查,我将不得不复制/粘贴我试图避免的全部内容。
bool isTypeA;
isTypeA ? return BlocBuilder< BlocA, BlocAState>(...) : return BlocBuilder< BlocB, BlocBState>(...)
First, make a method (could even be a local method in your build function) to return a widget from your items, no matter where they came from:首先,创建一个方法(甚至可以是构建函数中的本地方法)从您的项目中返回一个小部件,无论它们来自何处:
Widget buildFromItems(List<ItemType> items) {
return // something that creates a view of your items, maybe a ListView
}
and then in your build function:然后在您的构建 function 中:
return isTypeA
? BlocBuilder<BlocA, BlocAState>(builder:
(context, Astate) => buildFromItems(Astate.ItemList))
: BlocBuilder<BlocB, BlocBState>(builder:
(context, Bstate) => buildFromItems(Bstate.ItemList));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.