当我想在主代码中使用模型dart文件时出错

gijlo24d  于 2023-06-27  发布在  其他
关注(0)|答案(1)|浏览(106)

我在用Flutter创建一个问答游戏。今天之前一切都很好。我在库中的模型目录下创建了一个question_model dart文件用于问题。在这个模型文件中,我有一个问题列表,我把问题写在里面。每次我想使用这个questionList时,它都会给我这个错误:未定义的名称'questionList'
这是我的questionList,位于/lib/model/question_model:

`class Question {
  String question;

  String answer1;

  String answer2;

  int trueAnswer;

  String imageAddress;

  Question(this.question, this.answer1, this.answer2, this.trueAnswer,
      this.imageAddress);

  List<Question> questionList = [
    Question('Where is Persian Gulf?', 'Iran', 'Iraq', 1,
        'assets/images/persiangulf.png'),
    Question('Which one is most population country in the world?', 'India',
        'China', 2, 'assets/images/most.png'),
    Question('Which one created GTA series?', 'Ubisoft', 'Rockstar', 1,
        'assets/images/GTA.png'),
    Question('Which one is a rock band?', 'Queen', 'Metallica', 1,
        'assets/images/guitar.png'),
  ];

}`

这就是我想要使用这个列表的方式:

`checkAnswer(){
    setState(() {});
    int myAnswer = isOnePressed?1:2;
    questionList[currentQuestionNumber];
  }`
nxagd54h

nxagd54h1#

一种方法是将问题列表声明为静态的,然后在外部使用引用使用它。要做到这一点,你可以更新你的代码如下:

static List<Question> questionList = [
    Question('Where is Persian Gulf?', 'Iran', 'Iraq', 1, 'assets/images/persiangulf.png'),
    Question('Which one is the most populous country in the world?', 'India', 'China', 2, 'assets/images/most.png'),
    Question('Which one created the GTA series?', 'Ubisoft', 'Rockstar', 1, 'assets/images/GTA.png'),
    Question('Which one is a rock band?', 'Queen', 'Metallica', 1, 'assets/images/guitar.png'),
  ];

然后按以下方式在函数中引用它

checkAnswer() {
  setState(() {});
  int myAnswer = isOnePressed ? 1 : 2;
  Question.questionList[currentQuestionNumber];
}

您也可以在问题类之外声明列表。这样你就不需要修改任何东西,除了把列表从类中剪切出来并粘贴到它下面。

相关问题