퀴즈앱3; 추상화

장윤찬·2021년 11월 10일
0

goal : 새파일에 클래스를 생성하여main.dart파일을 추상화하자.

main.dart파일에 코드가 너무길어지고 복잡해지면서, 가독성과 코드의 효율이 떨어진다. 추상화작업이 이를 방지해준다.

지난번에 만들어놓은 퀴즈앱의main.dart파일에서, 'question' 클래스의
객체 'q'에 총3개의 질문과 답을 저장했었다.

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

만약 질문의 수가 많아질수록,main.dart파일의 코드는 훨씬 더 복잡해질것이다. 또한, 질문을 변경할때마다main.dart파일을 수정해야할것이다.

추상화 작업

이를 방지하기 위해 추상화작업을 진행할 것이다.

새파일/Class 생성

먼저, 새 파일quiz를 생성하여 객체 'q'를 속성으로하는 'Quiz'클래스를 생성하자.

import 'question.dart';

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

Question.dart파일을 'import'하여 'Question'타입을 정의해줘야 한다.

새 파일의 Class/객체 생성

이제,main.dart파일에 'Quiz'클래스의 객체 'quiz'를 생성하자.

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

'Quiz'클래스는quiz.dart파일에 있으므로 quiz.dart파일을 'import'한다.

객체 적용

'q'는 'Quiz'클래스의 속성이므로,main.dart파일이 코드는 아래와 같이 변경된다.

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

0개의 댓글