퀴즈앱final

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

goal : 퀴즈앱을 최종적으로 완성시키자.

마지막 질문에 다다르면, 에러가 나거나 변화없는 모습이 아니라 팝업창이 나타나며, 창의 클릭버튼을 누르면 처음의 상태로 돌아가게 해야한다.

패키지 이용.

간단한 명령어를 통해 팝업창을 생성하도록 도와주는 'RFlutter Alert' 패키지를 이용할 것이다.
installing탭을 보며 나의 프로젝트에 통합했다.
https://pub.dev/packages/rflutter_alert/install

  • pubspec.yami파일 설정
  • main.dart파일내에서 'import'

'QuizBrain' 클래스 설정

quiz_brain.dart파일의 'QuizBrain' 클래스내에 두개의 메소드를 추가할 것이다.

'isFinished' 메소드 작성

마지막 질문에 다다랐는지 확인하기 위해서 'isFinished' 메소드를 작성하자.
마지막 질문에 다다랐으면 'true'값을, 그렇지 않으면 'false'값을 반환하자.

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

'reset' 메소드 작성

'questionNumber'속성값을 0으로 치환하는 'reset' 메소드를 작성하자.
'isFinished'메소드가 'true'값을 반환했을 경우 사용될 메소드이다._ ※

void reset() {
  _questionNumber = 0;
}

main.dart 파일 수정

main.dart파일 내에서 위에서 작성한 메소드를 이용하자.

'isFinished'메소드가 'true'값을 반환했을 경우, 팝업창을 표시하고, 'reset'메소드를 호출하며, 'scoreKeeper'변수를 빈값으로 치환하자.
'false'값을 반환할경우, 기존의 명령을 그대로 실행하자.
팝업창은 클래스가 제공하는 명령어를 통해 쉽게 표시할수 있었다.
https://pub.dev/packages/rflutter_alert

  • 변경전
void checkAnswer(bool userPickedAnswer) {
  bool correctAnswer = quizBrain.getCorrectAnswer();
  setState(() {
    if (userPickedAnswer == correctAnswer) {
      scoreKeeper.add(Icon(
        Icons.check,
        color: Colors.green,
      ));
    } else {
      scoreKeeper.add(Icon(
        Icons.close,
        color: Colors.red,
      ));
    }
    quizBrain.nextQuestion();
  });
}  
  • 변경후
void checkAnswer(bool userPickedAnswer) {                   
  bool correctAnswer = quizBrain.getCorrectAnswer();  
  setState(() {        
    if (quizBrain.isFinished() == true) {                 
      Alert(                                                 
        context: context,                                   
        title: 'Finished!',                                 
        desc: 'You\'ve reached the end of the quiz.',      
      ).show();                                             
      quizBrain.reset();                                    
      scoreKeeper = [];
    }                                                       
    else {                                                 
      if (userPickedAnswer == correctAnswer) {               
        scoreKeeper.add(Icon(                               
          Icons.check,                                       
          color: Colors.green,                               
        ));                                                
      } else {                                               
        scoreKeeper.add(Icon(                               
          Icons.close,                                       
          color: Colors.red,                                 
        ));                                                 
      }                                                     
      quizBrain.nextQuestion();                             
    }                                                       
  });                                                      
}                                                           

이상으로 퀴즈앱을 최종적으로 완성했다. 아래는 퀴즈앱을 위해 작성한 전체코드이다.

  • 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 - 1) {
      _questionNumber++;
    }
  }

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

  bool getCorrectAnswer() {
    return _questionBank[_questionNumber].questionAnswer;
  }
  
  bool isFinished() {
    if (_questionNumber >= _questionBank.length - 1) {
      return true;
    } else {
      return false;
    }
  }
  
  void reset() {
    _questionNumber = 0;
  }
}
  • main.dart파일
import 'package:flutter/material.dart';            
import 'package:rflutter_alert/rflutter_alert.dart';       
import 'quiz_brain.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 = [];                               
  
  void checkAnswer(bool userPickedAnswer) {                 
    bool correctAnswer = quizBrain.getCorrectAnswer();       
                                                        
    setState(() {                                           
      if (quizBrain.isFinished() == true) {                 
        Alert(                                               
          context: context,                                 
          title: 'Finished!',                               
          desc: 'You\'ve reached the end of the quiz.',     
        ).show();   
        
        quizBrain.reset();                                                  
        scoreKeeper = [];                             
      } else {                                               
        if (userPickedAnswer == correctAnswer) {             
          scoreKeeper.add(Icon(                             
            Icons.check,                                     
            color: Colors.green,                            
          ));                                               
        } else {                                       
          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: TextButton(                               
              style: ButtonStyle(                           
                backgroundColor: MaterialStateProperty.all(Colors.green),   
              ),                                             
              child: Text(                                   
                'True',                                    
                style: TextStyle(                           
                  color: Colors.white,                       
                  fontSize: 20.0,                           
                ),                                                           
              ),                                             
              onPressed: () {                               
                //The user picked true.                     
                checkAnswer(true);                           
              },                                       
            ),                                               
          ),                                                 
        ),                                             
        Expanded(                                                           
          child: Padding(                                                   
            padding: EdgeInsets.all(15.0),                                  
            child: TextButton(                                              
              style: ButtonStyle(                                           
                  backgroundColor: MaterialStateProperty.all(Colors.red)),   
              child: Text(                                                  
                'False',                                                    
                style: TextStyle(                                           
                  fontSize: 20.0,                                           
                  color: Colors.white,                                      
                ),                                                           
              ),                                                             
              onPressed: () {                                               
                //The user picked false.                                    
                checkAnswer(false);                                         
              },                                                            
            ),                                                               
          ),                                                                 
        ),                                                                   
        Row(                                                                
          children: scoreKeeper,                                            
        )                                                                    
      ],                                                                     
    );                                                                       
  }                                                                         
}                                                                           

실행화면

profile
Flutter 학습 일기

0개의 댓글