【问题标题】:(Dart/Flutter) Pull one item from shuffled list without regenerating the list(Dart/Flutter)从随机列表中拉出一项而不重新生成列表
【发布时间】:2019-11-11 22:55:07
【问题描述】:

我是 Flutter 新手,这是我自己的第一个应用项目,但我什么也做不了。

我想打乱一个列表,以便它以随机顺序显示问题,但一次一个,我不希望有任何重复。当我尝试这样做时,我每次都会重新生成一个新的随机列表,有没有办法只生成一次,然后一次从中提取一个问题,而不重复问题?

我有一个名为“_questionBankEasy”的列表,我想从中提取 15 个项目。 我使用它是因为这似乎与我能找到的答案一样接近:List.shuffle() in Dart?

//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() 的“下一步”按钮时,我有时会得到一个重复的问题。可以解决吗?

【问题讨论】:

  • 能否请您使用显示问题的页面类完成示例?最好在有状态小部件的 initState() 方法内的单独变量中初始化您的问题,然后将它们打乱并调用类似 removeLast() 之类的东西,这将弹出并从该列表的末尾返回一项。
  • 谢谢你的回答,我已经给出了完整的例子。我试图做 removeLast() 但我无法让它工作,所以我可能缺少一些东西你能举个例子吗?您的意思是在 initState() 中制作列表和随机播放,然后在按下按钮时使用 removeLast() 调用它? (这就是我一直试图做的,但失败了)

标签: list random flutter dart shuffle


【解决方案1】:

一个可以在模拟器中运行的非常基本的示例。 在代码中添加了cmets,请阅读。

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'),
              )
            ],
          ),
        ),
      ),
    );
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-24
    • 2021-03-04
    • 2020-07-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多