# Quizzler with Flutter

# 0. Final Product

  • Quiz를 맞추고 스코어를 기록하는 App
  • 생각보다 어렵다

image-20220127105613840

# 1. Question

question.dart

class Question {
  String questionText;
  bool questionAnswer;

  Question(String q, bool a) {
    questionText = q;
    questionAnswer = a;
  }
}
1
2
3
4
5
6
7
8
9
  • Question 클래스

# 2. Quiz Brain

quiz_brain.dart

import 'question.dart';

class QuizBrain {
  int _questionNumber = 0;
  List<Question> _questionBank = [
    Question('Some cats are actually allergic to humans', true),
    Question('You can lead a cow down stairs but not up stairs.', false),
    Question('Approximately one quarter of human bones are in the feet.', true),
    Question('A slug\'s blood is green.', true),
    Question('Buzz Aldrin\'s mother\'s maiden name was \"Moon\".', true),
    Question('It is illegal to pee in the Ocean in Portugal.', true),
    Question(
        'No piece of square dry paper can be folded in half more than 7 times.',
        false),
    Question(
        'In London, UK, if you happen to die in the House of Parliament, you are technically entitled to a state funeral, because the building is considered too sacred a place.',
        true),
    Question(
        'The loudest sound produced by any animal is 188 decibels. That animal is the African Elephant.',
        false),
    Question(
        'The total surface area of two human lungs is approximately 70 square metres.',
        true),
    Question('Google was originally called \"Backrub\".', true),
    Question(
        'Chocolate affects a dog\'s heart and nervous system; a few ounces are enough to kill a small dog.',
        true),
    Question(
        'In West Virginia, USA, if you accidentally hit an animal with your car, you are free to take it home to eat.',
        true),
  ];

  void nextQuestion() {
    if (_questionNumber < _questionBank.length) {
      _questionNumber += 1;
    }
  }

  bool isFinished() {
    if (_questionNumber == _questionBank.length) {
      return true;
    } else {
      return false;
    }
  }

  void resetQuestionNumber() {
    _questionNumber = 0;
  }

  String getQuestionText() {
    return _questionBank[_questionNumber].questionText;
  }

  bool getQuestionAnswer() {
    return _questionBank[_questionNumber].questionAnswer;
  }
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
  • _questionBank _를 이용해서 private으로 유지해준다. 데이터양, 출처에 따라 별도 파일로 관리해 줄 필요가 있다. Question 클래스의 리스트를 만든다.
  • nextQuestion 다음질문으로 넘어가준다. 질문의 끝까지 왔다면은 이동하지 않는다.
  • isFinished를 통해서 끝까지 온지를 확인 후 resetQuestionNumber를 해줄 수 있다.

# 3. Main

`main.dart

import 'package:flutter/material.dart';
import 'quiz_brain.dart';
import 'package:rflutter_alert/rflutter_alert.dart';

QuizBrain quizBrain = QuizBrain();

void main() => runApp(Quizzler());

class Quizzler extends StatelessWidget {
  
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        backgroundColor: Colors.grey.shade900,
        body: SafeArea(
          child: Padding(
            padding: EdgeInsets.symmetric(horizontal: 10.0),
            child: QuizPage(),
          ),
        ),
      ),
    );
  }
}

class QuizPage extends StatefulWidget {
  
  _QuizPageState createState() => _QuizPageState();
}

class _QuizPageState extends State<QuizPage> {
  List<Icon> scoreKeeper = [
    Icon(Icons.check, color: Colors.green),
  ];

  int scoreNumber = 0;

  void checkFinish() {
    bool isFinished = quizBrain.isFinished();
    print(isFinished);
    if (isFinished) {
      Alert(
              context: context,
              title: "End of the Quiz",
              desc: "Your score is $scoreNumber")
          .show();
      quizBrain.resetQuestionNumber();
      scoreKeeper.clear();
      scoreNumber = 0;
    } else {}
  }

  void checkAnswer(bool userPickedAnswer) {
    bool correctAnswer = quizBrain.getQuestionAnswer();

    if (userPickedAnswer == correctAnswer) {
      setState(() {
        scoreKeeper.add(Icon(Icons.check, color: Colors.green));
        scoreNumber += 1;
        quizBrain.nextQuestion();
      });
    } else {
      setState(() {
        scoreKeeper.add(Icon(Icons.close, color: Colors.red));
        quizBrain.nextQuestion();
      });
    }
  }

  
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: <Widget>[
        Expanded(
          flex: 5,
          child: Padding(
            padding: EdgeInsets.all(10.0),
            child: Center(
              child: Text(
                quizBrain.getQuestionText(),
                textAlign: TextAlign.center,
                style: TextStyle(
                  fontSize: 25.0,
                  color: Colors.white,
                ),
              ),
            ),
          ),
        ),
        Expanded(
          child: Padding(
            padding: EdgeInsets.all(15.0),
            child: FlatButton(
              textColor: Colors.white,
              color: Colors.green,
              child: Text(
                'True',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 20.0,
                ),
              ),
              onPressed: () {
                checkAnswer(true);
                checkFinish();
              },
            ),
          ),
        ),
        Expanded(
          child: Padding(
            padding: EdgeInsets.all(15.0),
            child: FlatButton(
                color: Colors.red,
                child: Text(
                  'False',
                  style: TextStyle(
                    fontSize: 20.0,
                    color: Colors.white,
                  ),
                ),
                onPressed: () {
                  checkAnswer(false);
                  checkFinish();
                }),
          ),
        ),
        Row(children: scoreKeeper)
      ],
    );
  }
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
  • List<Icon> scoreKeeper 를 통해서 스코어 아이콘을 기록한다.
  • int scoreNumber = 0; 를 통해서 스코어 int를 기록한다.
  • 전체 형태는 flex5 - flex1 - flex1 - row의 Column이다.
  • QuizBrain quizBrain = QuizBrain(); 를 통해 instance를 만든다. 처음 _questionNumber값이 0으로 잡혀있기 때문에 method를 사용해 quiz를 진행하고 .nextQuestion을 통해 다음 문제로 이동한다.