Sage-Code Laboratory

Quiz

Application example tutorial

How to make a simple quiz with Yes/No answers:
This is a quiz example which contain three files: main.dart, questions.dart and quiz.dart.
// main.dart
  // this imports default Flutter dart package
  import 'package:flutter/material.dart';
  
  // this imports a file containing the quiz questions class
  import 'quiz.dart';
  
  // this imports an external package to display svg images in our app
  import 'package:flutter_svg/flutter_svg.dart';
  
  // the main function returns our QuizApp() class and displays in as our entire app
  
  const Color color_backround = Color.fromARGB(255, 34, 18, 90);
  
  void main() => runApp(QuizApp());
  
  //This is the QuizApp class we refered to in the preview comment //above, it extents the Flutter statelessWidget class and overides //it with our own functionality using the '@override' notation
  class QuizApp extends StatelessWidget {
    @override
    Widget build(BuildContext context) {
      return Container(
        child: MaterialApp(
          home: Scaffold(
            backgroundColor: color_backround,
            body: SafeArea(
              child: Padding(
                padding: EdgeInsets.symmetric(horizontal: 10.0),
                child: QuizPage(),
              ),
            ),
          ),
        ),
      );
    }
  }
  // Note that the above class calls the QuizPage class
  
  //Here in the QuizPage class, we build teh widgets that actually //displays the questions and buttons
  class QuizPage extends StatefulWidget {
    @override
    _QuizPageState createState() => _QuizPageState();
  }
  
  class _QuizPageState extends State {
  // a variable to store our scores
    List scores = [];
  
  // this creates an object of the Quiz class we import
    Quiz quizClass = Quiz();
  
  // this is a variable to keep track of the quiz if completed
    bool completed = false;
  
  // this function checks the user answer if correct
    void checkAnswer(bool userAnswer) {
      bool correctAns = quizClass.getQuestionAnswer();
      setState(() {
        if (quizClass.nextQuestion() == true) {
          print('next question');
          print(quizClass.nextQuestion());
          completed = true;
          if (userAnswer == correctAns) {
            scores.add(Icon(
              Icons.check,
              size: 50,
              color: Colors.green,
            ));
          } else {
            scores.add(Icon(
              Icons.close,
              size: 50,
              color: Colors.red,
            ));
          }
        } else {
          print('setting marks');
          if (userAnswer == correctAns) {
            scores.add(Icon(
              Icons.check,
              size: 50,
              color: Colors.green,
            ));
          } else {
            scores.add(Icon(
              Icons.close,
              size: 50,
              color: Colors.red,
            ));
          }
        }
      });
    }
  
  //this is another overriden widget that calls the buildQuestionPage
  ////function to setup our page
    @override
    Widget build(BuildContext context) {
      return buildQuestionsPage();
    }
  
  // this function shows the questions when we start the app, and
  ////showind the completed secttion if the quiz has been completed
    Column buildQuestionsPage() {
      if (completed) {
        return Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            Expanded(
              flex: 5,
              child: Padding(
                padding: EdgeInsets.all(10.0),
                child: Center(
                  child: Column(
                    children: [
                      SvgPicture.asset('assets/completed.svg', width: 200.0),
                      Text(
                        'You have successfully completed the quiz',
                        textAlign: TextAlign.center,
                        style: TextStyle(color: Colors.white, fontSize: 25.0),
                      ),
                    ],
                  ),
                ),
              ),
            ),
            Expanded(
              child: Padding(
                padding: EdgeInsets.all(10.0),
                child: ElevatedButton(
                    style: ElevatedButton.styleFrom(
                      shape: BeveledRectangleBorder(
                          borderRadius: BorderRadius.circular(12)),
                    ),
                    onPressed: () {
                      setState(() {
                        completed = false;
                        scores = [];
                        quizClass.startOver();
                      });
                    },
                    child: Text(
                      'Start Over',
                      style: TextStyle(color: Colors.white, fontSize: 20.0),
                    )),
              ),
            ),
            SafeArea(
              child: Row(
                children: scores,
              ),
            )
          ],
        );
      } else {
        return Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Expanded(
              flex: 5,
              child: Padding(
                padding: EdgeInsets.all(10.0),
                child: Center(
                  child: Text(
                    quizClass.getQuestionText(),
                    textAlign: TextAlign.center,
                    style: TextStyle(color: Colors.white, fontSize: 25.0),
                  ),
                ),
              ),
            ),
            Expanded(
              child: Padding(
                padding: EdgeInsets.all(10.0),
                child: ElevatedButton(
                    style: ElevatedButton.styleFrom(
                      shape: BeveledRectangleBorder(
                          borderRadius: BorderRadius.circular(12)),
                    ),
                    onPressed: () {
                      checkAnswer(true);
                    },
                    child: Text(
                      'True',
                      style: TextStyle(color: Colors.white, fontSize: 20.0),
                    )),
              ),
            ),
            Expanded(
              child: Padding(
                padding: EdgeInsets.all(10.0),
                child: ElevatedButton(
                    style: ElevatedButton.styleFrom(
                      shape: BeveledRectangleBorder(
                          borderRadius: BorderRadius.circular(12)),
                    ),
                    onPressed: () {
                      checkAnswer(false);
                    },
                    child: Text(
                      'False',
                      style: TextStyle(color: Colors.white, fontSize: 20.0),
                    )),
              ),
            ),
            SafeArea(
              child: Row(
                children: scores,
              ),
            )
          ],
        );
      }
    }
  }

// question.dart
    class Question {
    String questionText = "";
    bool questionAnswer = true;

    Question({required String qtn, required bool ans}) {
      questionText = qtn;
      questionAnswer = ans;
    }
  }

// quiz.dart
    // We import the questions class we have already created
    import 'questions.dart';
    
    // The Quiz class initialize private properties and methods for our questions
    class Quiz {
    // We use this private variable to keep track of the current question number.
      int _questionNumber = 0;
    
    // In this List variable we will store our questions and answers
      List _questionList = [
        Question(
            qtn:
                'Does Canada have a larger land area, excluding water, than the US?',
            ans: false),
        Question(
            qtn: 'Does Greenland is a country on the North American continent?',
            ans: false),
        Question(
            qtn: 'Does Switzerland has the higher cost of living in the world?',
            ans: true),
        Question(
            qtn: 'Does India have the largest population in the world?',
            ans: false),
        Question(
            qtn: 'Does whole Africa has a larger population than China?',
            ans: false),
      ];
    
    // this function will access the question number and increment it
    // also it will let us know if the questions have been completed
      dynamic nextQuestion() {
        if (_questionNumber < _questionList.length - 1) {
          print(_questionNumber);
          _questionNumber++;
        } else {
          bool completed = true;
          return completed;
        }
      }
    
    // this function will return the question text of the
    //specific question number text when called in the main.dart
      String getQuestionText() {
        return _questionList[_questionNumber].questionText;
      }
    
    // this function will return the answer of the
    //specific question number when called in the main.dart
      bool getQuestionAnswer() {
        return _questionList[_questionNumber].questionAnswer;
      }
    
    // this function will set the question
    //number back the 0 when the quiz is restarted
      int startOver() {
        return _questionNumber = 0;
      }
    }
Responsive image    Responsive image

Back to: Flutter index