简体   繁体   中英

Changing the bloc of a BlocBuilder depending on a parameter

I have a BlocBuilder which allows me to build a list of elements. The considered Bloc of the BlocBuilder has in its state the List<T> of the elements to be displayed.

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). 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. 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.

I wanted to know if it was possible to change the type of the Bloc just with a ternary operator. 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.

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:

return isTypeA 
    ?  BlocBuilder<BlocA, BlocAState>(builder:
          (context, Astate) => buildFromItems(Astate.ItemList))
    :  BlocBuilder<BlocB, BlocBState>(builder:
          (context, Bstate) => buildFromItems(Bstate.ItemList));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM