Home > Software engineering >  onPressed does not execute Function even after using setState
onPressed does not execute Function even after using setState

Time:12-25

I created a function below

nextQuestion() {
    setState(() {
      questionIndex  ;
    });
    print('pressed');
  }

I then created the class below and passed in the method above a constructor for an onPressed property

class Answer extends StatelessWidget {
  final String answer;
  final VoidCallback? selectHandler;
  // ignore: use_key_in_widget_constructors
  const Answer({required this.answer, this.selectHandler});

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: selectHandler,
      child: SizedBox(
        width: double.infinity,
        child: Center(
          child: Text(
            answer,
          ),
        ),
      ),
    );
  }
}

I then used the constructor of the class and passed in the function to update the text on my screen which is in a list with questionIndex as its index

Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Question(question: questions[questionIndex]),
          Answer(selectHandler: nextQuestion(), answer: 'Yellow'),
          Answer(selectHandler: nextQuestion(), answer: 'Yellow'),
          Answer(selectHandler: nextQuestion(), answer: 'Yellow'),
        ],
      ),

This is not working/Is not updating the text on my screen after pressing the button

CodePudding user response:

I've recreated the code and it works for me with a few exceptions:

  1. Answer(selectHandler: nextQuestion(), answer: 'Yellow'), is wrong. You have to use selectHandler: nextQuestion (no () after the function)
  2. Use the answer widget inside another stateful widget.

If you did all these and it still doesn't work run flutter clean followed by flutter pub get (close the debug session first)

And if that doesn't work, the problem is with your questions widget. Can you share the code?

  • Related