Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Flutter, bug in classes

I’m new to flutter/dart and I don’t know if I’m crazy or if it’s a bug.

In main.dart I call Quiz’s function getQuestionText and getQuestionAnswer, getQuestionText works as expected but the other doesn’t work, if returns me always the first result of the list. I just placed a debugPrint() and as expected getQuestionText() prints the correct number, getQuestionAnswer() always print 0, how is that possible?

class Quiz {
  int _questionNumber = 0;

  List<Question> _questions = [
    Question('Some cats are actually allergic to humans', true),
    Question('You can lead a cow down stairs but not up stairs.', false),
  ];

  void nextQuestion() {
    if (_questionNumber < _questions.length - 1) {
      _questionNumber++;
    }
  }

  String getQuestionText() {
    print('$_questionNumber'); // <-- print the correct number
    return _questions[_questionNumber].questionText;
  }

  bool getQuestionAnswer() {
    print('$_questionNumber'); // <-- always print 0
    return _questions[_questionNumber].questionAnswer;
  }
}

Here how I call the functions

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

void checkAnswer(bool userAnswer) {
    bool correctAnswer = Quiz().getQuestionAnswer();

    setState(() {

      if (userAnswer == correctAnswer) {
        // right answer
      } else {
          // wrong pick
        );
      }
      quiz.nextQuestion();
      
    });
  }

>Solution :

The problem is that you always create a fresh instance of your class Quiz by calling bool correctAnswer = Quiz().getQuestionAnswer(); inside checkAnswer().

Try to store the Quiz instance ouside:

const myQuiz = Quiz();

void checkAnswer(bool userAnswer) {
  bool correctAnswer = myQuiz.getQuestionAnswer();

  setState(() {
    if (userAnswer == correctAnswer) {
      // right answer
    } else {
      // wrong pick
    }

    myQuiz.nextQuestion();
  });
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading