퀴즈앱2; Question 'Class'

장윤찬·2021년 11월 8일
0
post-thumbnail

goal : Class를 생성하여 데이터타입이 다른 두개의 'List'를 하나로 만들자

퀴즈앱을 만들때, 아래와 같이 두개의 List변수를 생성했다.

List<String> questions = [
    'You can lead a cow down stairs but not up stairs.',
    'Approximately one quarter of human bones are in the feet.',
    'A slug\'s blood is green.'
  ];
List<bool> answers = [false, true, true];

이 두개의 변수를 하나로 만들어보자.

lib폴더에 새 클래스를 만들question.dart파일을 생성하자.
'Question' 클래스에 'String'과 'bool'타입의 변수를 선언해야한다.

Class Question {
  String questiontext;
  bool questionanswer;
}

클래스안에 생성자를 추가하자.

class Question {
  String questiontext;
  bool questionanswer;

  Question({String t, bool a}) {
    questiontext = t;
    questionanswer = a;
  }
} // dart에서 생성자명은 클래스명과 같다.

이제main.dart파일에서 List String questions과 List bool answers 변수를 하나로 설정하자.

import 'question.dart';
'
'
'
List<Question> q = [
    Question(t: 'You can lead a cow down stairs but not up stairs.', a: false),
    Question(
        t: 'Approximately one quarter of human bones are in the feet.',
        a: true),
    Question(t: 'A slug\'s blood is green.', a: true)
  ];

결과적으로 코드는 다음과같이 수정되어야한다.

  • 변경전
child: Text(
  questions[questionNumber],
'
'
onPressed: () {
  if (answers[questionNumber] == true) {
    print('correct');
'
'
onPressed: () {
  if (answers[questionNumber] == false) {
    print('correct');
'
'
  • 변경후
child: Text(
  q[questionNumber].questiontext,
'
'
onPressed: () {
  if (q[questionNumber].questionanswer == true) {
    print('correct');
'
'
onPressed: () {
  if (q[questionNumber].questionanswer == false) {
    print('correct');
'
'
profile
Flutter 학습 일기

0개의 댓글