dimanche 25 octobre 2020

Flutter: How can I update a variable to display some text, have a delay, then update another variable also displaying text?

I'm very new to Flutter and Stack Overflow, so I apologize in advance if my question comes off as silly. I'm currently trying to create an app that helps a user memorize French vocabulary. I want the user to be able to click a button to check their answer, see immediately whether their answer is right or wrong, and then a have a delay of a few seconds to view their corrected answer, before the question changes. Here's a snippet of my code:

Padding(
          padding: const EdgeInsets.fromLTRB(10.0, 100.0, 0.0, 0.0),
          child: RaisedButton(
            color: Colors.white,
            child: Text(
              'Check Answer.',
              style: TextStyle(
                fontFamily: 'Oswald',
                fontStyle: FontStyle.italic,
                fontSize: 18.0,
                fontWeight: FontWeight.bold,
              ),
            ),
            onPressed: (){
              answer = myController.text;
              isCorrect = (answer == answers.elementAt(element));
              isCorrect == true ? answerMessage = "Correct!" : answerMessage = "Sorry, that answer was incorrect.";
              Future.delayed(const Duration(milliseconds: 5000), () {
                setState(() {
                  element = question.nextInt(3);
                  word = questions.elementAt(element);
                });
              });
            },
          ),
        ),

For reference, I've created two arrays, one for questions and one for the answers and the variable 'element' is simply a random number that is plugged into both arrays to generate the question and the expected answer.

I get the user's answer using a controller in a TextField widget and then compare it to the appropriate element in the 'answers' array. Based on whether the above condition is true or false, I update the 'answerMessage' variable to display on the screen whether the answer is correct or not. After this, I have tried to put a delay of around 5 seconds before the 'element' variable is given a new random integer value (which corresponds to a new question being randomly picked from my 'questions' array) before the 'word' variable that is being displayed on screen is updated to reflect the new question. I can't find any issues with my code, yet for some reason, my program instead waits 5 seconds before even displaying whether the user is correct or not, and then immediately updates the question, which defeats the delay's purpose as the whole point of the delay is for the user to have some time to see if their answer is correct before moving on to the next question.

Whew! I'm sorry if this came across as long-winded but I wanted to make sure to not miss out on any details. Thanks in advance!




Aucun commentaire:

Enregistrer un commentaire