首页 > 解决方案 > 为什么我不能将对象中的信息打印到控制台上

问题描述

为什么我不能在 dart 中打印以下语句:

print(questionBank[1].questionAnswer);
print(questionBank.length);

==================================================== ===

class Question {
  String questionText;
  bool questionAnswer;

  Question({String ques, bool ans}) {
    questionText = ques;
    questionAnswer = ans;
  }
}
      
        void main{
            List<Question> questionBank = [
                Question(
                    ques: 'You can lead a cow down stairs but not up stairs.', ans: false),
                Question(
                    ques: 'Approximately one quarter of human bones are in the feet.',
                    ans: true),
                Question(ques: 'A slug\'s blood is green.', ans: true),
              ];
            
              print(questionBank[1].questionAnswer);
              print(questionBank.length);
        }

标签: flutterdart

解决方案


这是您的模型插入 toString 方法,通过右键单击您的模型>genrate>toString() '(Android studio)'

class Question {
  String questionText;
  bool questionAnswer;

  Question({String ques, bool ans}) {
    questionText = ques;
    questionAnswer = ans;
  }


  @override
  String toString() {
    return 'Question{questionText: $questionText, questionAnswer: $questionAnswer}';
  }

}

然后像这样使用:

debugPrint(questionBank[1].questionAnswer.toString());

推荐阅读