在颤动中动态创建与其他变量长度一样多的变量

Create variable dynamically as much as other variable's length in flutter

我正在制作一个问题应用程序。问题不是静态的,答案是动态的,它们可以超过 4 个。出于演示目的,我有一个像这样的虚拟变量:

final List<Map<String, dynamic>> questions = [
    {
      'questionText': 'what is your personality?',
      'answers': [
        'Calm',
        'cheerful',
        'Romantic',
        'Sporty',
      ]
    },
    {
      'questionText': 'What is your favorite color?',
      'answers': [
        'Blue',
        'Red',
        'Green',
        'Yellow',
        'White',
      ]
    },
  ];

我暂时将所选答案存储在以下变量中:

List<String> selectedAnswer = [];

并且当按下下面的按钮时,它可以将它的值存储到变量中。

children: List.generate(question['answers'].length, (index) {
  var selected = false;
  for (var i = 0; i < selectedAnswer.length; i++) {
    if (selectedAnswer[i] == question['answers'][index]) {
      selected = true;
    }
  }
return GestureDetector(
  onTap: () => setState(() {
    if (selected) {
      selectedAnswer.remove(question['answers'][index]);
    } else {
      selectedAnswer.add(question['answers'][index]);
    }
  }),
  child: Row(
    mainAxisSize: MainAxisSize.min,
    children: [
      Container(
        width: 30,
        height: 30,
        padding: const EdgeInsets.all(4),
        decoration: BoxDecoration(
            shape: BoxShape.circle,
            color: Colors.transparent,
            border: Border.all(color: primaryColor)),
        child: Container(
            decoration: BoxDecoration(
          shape: BoxShape.circle,
          color: (selected) ? primaryColor : Colors.transparent,
        )),
      ),
      SizedBox(width: Spacing.smallPadding),
      Text(question['answers'][index],
          style: Theme.of(context)
              .textTheme
              .headline6!
              .copyWith(fontWeight: FontWeight.w600)),
    ],
  ),
),

而我的真正目标是将每个问题的选定值存储到它自己的变量中。这样我就可以很轻松的把它发到一个API,但是问题是问题可以比上面的多。可以吗?如果不能,那你能给我推荐最好的方法吗

有什么需要告诉我

你的问题不是很清楚是什么问题,但如果我理解正确的话,你有未知数量的问题,每个问题都有未知数量的答案。您希望能够为他们创建相关的小部件,并以一种以后易于提取并传递给某些 API 的方式存储每个问题的答案。正确吗?

考虑到这一点,我将使用稍微不同的结构来保存所选答案:

final Map<String, String> answers = {
  'What is your favorite color': 'Pink',
  'Who is your favorite person': 'Uncle Sam',
};

// Add an answer to the collection.
answers[questionId] = answerId;

在实践中,我会这样做:

// questionnaire_widget.dart
class Questionnaire extends StatelessWidget {
  @override
  build(BuildContext) {
    return Column(
      children: questions.entries.map((q) => Question(q)).toList();
    );
  }
}

// question_widget.dart
class Question extends StatelessWidget {
  final QuestionModel question;

  @override
  build(BuildContext) {
    return Column(
      children: [
        Text(question.questionText),
        question.answers.entries.map((answer) => Answer(
          question.questionId,
          answer,
        )).toList();
  }
}

// answer_widget.dart
class Answer extends StatelessWidget {
  final AnswerModel answer;
  final String QuestionId;

  @override
  build(BuildContext) {
    return TextButton(
      child: Text(answer.answerText),
      onPressed: () {
        // Store the answer in the answers collection.
        // For example: globalAnswersVariable[questionId] = answer;
      },
    );
  }
}

需要注意的一件事是,您可能应该在这里使用一些状态管理,而不是全局变量。例如,您可以使用 Riverpod,这使得从任何小部件访问提供程序变得容易。

另外,我在数据结构中添加了一个假设的 questionId,因为这是一个更可靠的解决方案。 (图像必须支持多种语言。或修复拼写错误。)通常,您应该依赖 ID,而不是数据结构中的实际值。