为什么我无法在控制台上打印对象中的信息

时间:2020-06-27 10:43:07

标签: flutter dart

为什么我不能在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);
        }

2 个答案:

答案 0 :(得分:1)

这是您的模型插入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());

答案 1 :(得分:1)

您只需要像这样覆盖方法toString

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

然后您可以:

print(yourObject);