(Дротик / Флаттер) Вытащите один предмет из перемешанного списка, не восстанавливая список - PullRequest
0 голосов
/ 01 июля 2019

Я новичок во флаттере, и это мой первый собственный проект приложения, и я не могу заставить одну вещь работать.

Я хочу перетасовать список, чтобы он отображал вопросы в случайном порядке, но по одному, и я не хочу, чтобы были какие-либо дубликаты. Когда я пытаюсь сделать это, я заново создаю новый перемешанный список, есть ли способ просто сгенерировать его один раз, а затем извлечь из него один вопрос за раз, не повторяя при этом вопросы?

У меня есть список с именем "_questionBankEasy", длина которого составляет 15 пунктов, из которых я хочу получить. Я использовал это, потому что это, казалось, было так близко к ответу, как я мог найти: List.shuffle () в Дарт?

//inside question_bank.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);
    }

//inside questionscreen_text.dart
class QuestionScreenText extends StatelessWidget {
  QuestionScreenText();

  @override
  Widget build(BuildContext context) {
    if (selectedDifficulty == Difficulty.easy) {
      return Text(
        QuizGenerator().getQuestionTextEasy(),
        style: kQuestionLable,
        textAlign: TextAlign.center,
      );
    }

//inside question_screen.dart
class QuestionScreen extends StatefulWidget {
  @override
  _QuestionScreenState createState() => _QuestionScreenState();
}
class _QuestionScreenState extends State<QuestionScreen> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: kDarkGreyRed,
      body: Column(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Padding(
            padding: const EdgeInsets.all(25.0),
            child: QuestionScreenText(),
            ),
          IconButton(
            padding: EdgeInsets.all(0),
            icon: Icon(Icons.close),
            iconSize: 100.0,
            color: kWhiteColour,
            disabledColor: Colors.transparent,
            highlightColor: Colors.transparent,
            splashColor: kPinkColour,
            onPressed: () {
              setState(() {
              QuizGenerator().nextQuestion();
            });
          },
        ),
      ]
    );
  }
}

Я ожидал, что это сработает, но это не так, в результате код извлекает один элемент из списка, но когда я нажимаю кнопку «Далее», которая вызывает nextQuestion () Я иногда получить повторяющийся вопрос. Можно ли это исправить?

1 Ответ

0 голосов
/ 01 июля 2019

Очень простой пример, который вы можете запустить в своем эмуляторе.Добавлены комментарии в коде, пожалуйста, прочитайте их.

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

// List of questions from some data point
List<String> questions = [
  'Question 1',
  'Question 2',
  'Question 3',
  'Question 4',
  'Question 5',
  'Question 6',
  'Question 7',
  'Question 8',
  'Question 9',
  'Question 10',
  'Question 11',
  'Question 12',
  'Question 13',
];

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Page(),
    );
  }
}

class Page extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _PageState();
}

class _PageState extends State<Page> with SingleTickerProviderStateMixin {
  // Variables to hold questions list and current question
  List<String> _pageQuestions;
  String _currentQuestion;

  @override
  void initState() {
    // Initialize pageQuestions with a copy of initial question list
    _pageQuestions = questions;
    super.initState();
  }

  void _shuffleQuestions() {
    // Initialize an empty variable
    String question;

    // Check that there are still some questions left in the list
    if (_pageQuestions.isNotEmpty) {
      // Shuffle the list
      _pageQuestions.shuffle();
      // Take the last question from the list
      question = _pageQuestions.removeLast();
    }
    setState(() {
      // call set state to update the view
      _currentQuestion = question;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Container(
          padding: EdgeInsets.symmetric(horizontal: 20.0),
          child: ListView(
            shrinkWrap: true,
            primary: false,
            children: <Widget>[
              if (_pageQuestions.isNotEmpty && _currentQuestion == null)
                Text('Press the "NEXT QUESTION" button'),
              if (_pageQuestions.isEmpty) Text('No more questions left'),
              if (_pageQuestions.isNotEmpty && _currentQuestion != null)
                Text(
                    '${_currentQuestion} (Questions left: ${_pageQuestions.length})'),
              RaisedButton(
                onPressed: _shuffleQuestions,
                child: Text('NEXT QUESTION'),
              )
            ],
          ),
        ),
      ),
    );
  }
}

...