Home > Mobile >  setState() causing infinite loop in flutter
setState() causing infinite loop in flutter

Time:08-15

so I'm trying to create a loop that will add a string to a List from my Bloc, however whenever i successfully added the string into the list, every single time a setstate is ran the program runs the loop all over again and adds the string into the list, i think adding a boolean for the for loop could work, but is there a more efficient way to do this?? I only want the loop to run once, even when the build method is called again.

code:

Container(
          height: MediaQuery.of(context).size.height / 1.2,
          width: MediaQuery.of(context).size.width,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              ElevatedButton(
                  onPressed: () => setState(() {}),
                  child: Text("set state")),
              ElevatedButton(
                  onPressed: () {
                    BlocProvider.of<BlackjackkBloc>(context).add(
                        DrawCardEvent(deck_id: deckId!, draw_count: "1"));
                    setState(() {
                      dealerCards  ;
                      dealerVal  = 10;
                    });
                  },
                  child: Text("deal")),
              BlocBuilder<BlackjackkBloc, BlackjackkState>(
                  builder: (context, state) {
                if (state is BlackjackkDrawLoaded) {
                  for (int i = 0; i < state.bjdraw.cards.length; i  ) {
                    print("going $i");
                    cards.add(state.bjdraw.cards[i].image);
                    print("repeat");
                  }
                  return Column(
                    children: List.from(cards.map((name) => Text(name))),
                  );
                  /*return Text("${cards}");*/
                }
                return Text("o");
              }),
              Text("cards length = ${cards.length}"),
              Container(
                height: 150,
                width: 100 * dealerCards.toDouble(),
                child: ListView.builder(
                  physics: BouncingScrollPhysics(),
                  /*separatorBuilder: (context, index) => SizedBox(
                    width: 0.1,
                  ),*/
                  itemCount: dealerCards,
                  scrollDirection: Axis.horizontal,
                  itemBuilder: (BuildContext context, int index) {
                    return Container(
                      width: 100,
                      height: 150,
                      child: CachedNetworkImage(
                        imageUrl:
                            "https://deckofcardsapi.com/static/img/AS.png",
                      ),
                    );
                  },
                ),
              ),
              SizedBox(height: 30),
              SizedBox(
                height: 40,
              ),
              Text(
                "Dealer",
                style: desctext,
              ),
              SizedBox(height: 10),
              Text(playerCards.toString()),
              Text(
                dealerVal.toString(),
                style: cardtext,
              ),
              BlocBuilder<BlackjackkBloc, BlackjackkState>(
                builder: (context, state) {
                  if (state is BlackjackkShuffleLoaded) {
                    deckId = state.bjshuffle.deckId;
                    return Text(state.bjshuffle.deckId);
                  }
                  if (state is BlackjackkLoad) {
                    return CircularProgressIndicator();
                  }
                  return Text("blum load");
                },
              )
            ],
          ),
        ),

CodePudding user response:

Try add a buildWhen method in your blocBuilder that only builds if current state differ from previous state.

BuildWhen: (previous, current) { current.state != previous.state }

CodePudding user response:

Why are using setState within the bloc?

Emit a new state from the DrawCardEvent function and change your UI as per that state.

I guess you are using a bloc instead of a cubit. If you are new to the bloc, maybe start with cubit. Cubit is simple and is good enough in 99% of the business cases.

  • Related