Home > Mobile >  How to loop inside a BlocBuilder Flutter
How to loop inside a BlocBuilder Flutter

Time:08-11

Hey all so I'm trying to create a For Loop inside of the bloc builder, I'm trying to return a text the same amount as my List, My Code will explain this better.

BlocBuilder<BlackjackkBloc, BlackjackkState>(
                      builder: (context, state) {
                        if (state is BlackjackkDrawLoaded) {
                          print("Size of  ${state.bjdraw.cards.length}");
                          for (int i = 0; i < state.bjdraw.cards.length; i  ) {
                            print("going $i");
                            return Text(state.bjdraw.cards[i].image);
                          }
                        }
                        return Text("Empty");
                      },
                    )

So for example i have 3 values in my state.bjdraw.cards.length i would like to return 3 Text(state.bjdraw.cards[i].image)

so far in this code at the top at the print function before the loop, it is able to determine the length of the state.bjdraw.cards.length however when it enters the loop it seems that it only runs once and it doesn't loop the return Text 3 times. How can i return state.bjdraw.cards[i].image 3 times and it returns the inside of the text each time

CodePudding user response:

this happen because in first round of the loop, you return a value and it break the loop. so if you want to show all three text, you should do something like this:

List<Widget> texts = [];
for (int i = 0; i < state.bjdraw.cards.length; i  ) {
                            print("going $i");
                            texts.add(state.bjdraw.cards[i].image);
                          }
return Column(
children: texts);

CodePudding user response:

You need to set all the Text Widgets inside a Column or a Row. Otherwise you will get back only 1 Text Widget.

You can use the .map method to iterate through your card list. Would look like this:

 Column(
      children: cards
          .map(
            (card) => Text(card.image),
          )
          .toList(),
    );
  • Related