lundi 1 juillet 2019

(Dart/Flutter) Pull one item from shuffled list without regenerating the list

I'm new to flutter and this is my first own app project and I cant get one thing to work.

I want to shuffle a list so that it shows questions in a random order but one at a time and I don't want there to be any duplicates. When I try and do this I regenerate a new shuffled list each time, is there any way to just generate it once and then pull one question at a time from it, without it repeating the questions?

I've a list called "_questionBankEasy" that are 15 items long that I want to pull from. I used this because this seemed to be as close to an answer as I could find: List.shuffle() in Dart?

import 'dart:math' as math;

//shuffled list
List<String> shuffle(List questionBankEasy) {
  var random = math.Random();

  for (var i = questionBankEasy.length - 1; i > 0; i--) {
    var n = random.nextInt(i + 1);

    var temp = questionBankEasy[i];
    questionBankEasy[i] = questionBankEasy[n];
    questionBankEasy[n] = temp;
  }
  return questionBankEasy;
}

int _questionNumber = 0;

//generates a shuffled list
String getQuestionTextEasy() {
    return shuffle(_questionBankEasy)[_questionNumber];
  }

// pulls next question
void nextQuestion() {
    if (selectedDifficulty == Difficulty.easy &&
        _questionNumber < _questionBankEasy.length - 1) {
      _questionNumber++;
      print(_questionNumber);
    }

I expected this to work, but it didn't, the result is that the code pulls one item from the list but when I press on the "next" button that calls nextQuestion() I sometimes get a repeating question. Can this be fixed?




Aucun commentaire:

Enregistrer un commentaire