Nomad09
Nomad09

Reputation: 199

how to set a counter in a stateful widget from outside the widget

I have a stateful widget that is 2 counter buttons and a counter display between them.

class OneCounterTwoBulbs extends StatefulWidget {
  final int counter;
  const OneCounterTwoBulbs({Key? key, required this.counter}) : super(key: key);

  @override
  State<OneCounterTwoBulbs> createState() => _OneCounterTwoBulbsState();
}

class _OneCounterTwoBulbsState extends State<OneCounterTwoBulbs> {
  int friendlyCounter = 0;

 @override
  Widget build(BuildContext context) {
    return CounterAndButtons(
                    minusButton: Expanded(
                      child: PlusMinusButton(
                        onTap: () {
                          setState(() {
                            if (friendlyCounter > 0) {
                              friendlyCounter--;
                            }
                          });
                        },
                        icon: FontAwesomeIcons.minus,
                        bgColor: kBlueGrey900,
                        iconColor: kWhite,
                      ),
                    ),
                    counter: Counter(counter: '$friendlyCounter'),
                    plusButton: Expanded(
                      child: PlusMinusButton(
                        onTap: () {
                          setState(() {
                            friendlyCounter++;
                          });
                        },
                        icon: FontAwesomeIcons.plus,
                        bgColor: kBlueGrey900,
                        iconColor: kWhite,
                      ),
                    ),
                  ),

I'm using this widget multiple times throughout my app and I need to be able to specify what number the counter should start at from the parent stateful widget.

how do I make widget.counter = friendlyCounter inside the widget?

thanks so much

Upvotes: 1

Views: 325

Answers (1)

CCP
CCP

Reputation: 1236

parameter is not updating because with setState it will only rebuild the parameter/state/variables that are in the same screen/class widget where the setState is called so you have to raise your parameter to the parent screen then pass it to the child with constructor and create a constructor in your child for function onTap for example then in the parent screen you use that onTap and called setState inside

Upvotes: 1

Related Questions